JS: Iterate Over Map Object

By Xah Lee. Date: . Last updated: .

Iterate Over Map with for-of Loop

The syntax:

for (let [k,v] of map_instance) { … }

iterate over Map map_instance's elements. k is key, v is value.

let myMap = new Map([["a", 1], ["b", 2], ["c", 3]]);

// iterate over map with key and value
for (let [k, v] of myMap) {
  console.log(k, v);
}
// prints
// a 1
// b 2
// c 3

The syntax:

for (let x of map_instance) { … }

iterate over Map map_instance's elements. Each element is assigned to x as array.

let myMap = new Map([["a", 1], ["b", 2], ["c", 3]]);

// iterate over map elements
for (let pair of myMap) {
    console.log(pair, Array.isArray ( pair )); // each element is array
}

// prints
// [ 'a', 1 ] true
// [ 'b', 2 ] true
// [ 'c', 3 ] true

[see JS: for-of Loop]

Iterate Over Map with forEach Method

[see JS: Map.prototype.forEach]

JS Map Topic

  1. the Map Object Tutorial
  2. Map Object
  3. Map.prototype
  4. Iterate Over Map Object
  5. Convert Object to/from Map
  6. Map Filter
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog