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 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 JS: for-of Loop]

Iterate Over Map with forEach Method

[see JS: Map.prototype.forEach]

Map Topic

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

Or, Buy JavaScript in Depth

Ask me question on patreon