JavaScript: 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 the value of key, v is the value of 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 JavaScript: for-of Loop

Iterate Over Map with forEach Method

〔►see JavaScript: Map.prototype.forEach

Map Topic

  1. JavaScript: the Map Object Tutorial
  2. JavaScript: Map Object
  3. JavaScript: Map.prototype
  4. JavaScript: Iterate Over Map Object
  5. JavaScript: Convert Object to Map Data Type
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.