1
19

JavaScript: How to Iterate through JavaScript Map ES6

Reading Time: 2 minutes

There are 3 methods that are commonly use to iterate through Map in JavaScript and Nodejs. We will be discussing them here.

Iterating Methods

  • Pre ES6 Style
  • Iterate with For...of
  • Iterate with ForEach

Before we go into the details, we have a more in-dept post here on how to create and use JavaScript Map for basic understanding.

Pre ES6 Style

Since JavaScript Map object is only provided on ES6, we will illustrate a Map concept with a 2D array. Hence, in order to iterate, it is the same as how we iterate array.

// Create a array map to iterate over
var ageMap = [
  ['Person1', 11],
  ['Person2', 33],
  ['Person3', 44], 
  ['Person4', 66],
  [10000001, 11]
];

// Iterating 2D array
for (var i in ageMap){
  for (var m = 0; m < ageMap[i].length; m++){
    console.log(ageMap[i][m]);  
  }
} 

Iterate with For...of

Map as a built-in object has provided 3 methods to access its attribute. More information in MDN documentation. Hence, we will be able to select one of them that is best for your use case. Do not that when we are iterating over Map, it will always process in the insertion order.

  • Map.prototype.entries() -> return iterable of keys and values
  • Map.prototype.keys() -> return iterable of keys
  • Map.prototype.values() -> return iterable of values

Let’s look at an illustration on how to use each type of iteration below.

// Create a map to iterate over
const ageMap = new Map([
  ['Person1', 11],
  ['Person2', 33],
  ['Person3', 44], 
  ['Person4', 66],
  [10000001, 11]
]);

// Via Map.prototype.entries()
for (var [key, value] of ageMap.entries()) {
  console.log(`${key} = ${value}`);
}

// Via Map.prototype.keys()
for (let key of ageMap.keys()) {
  console.log(`${key} = ${ageMap.get(key)}`);
}

// Via Map.prototype.values()
for (let value of ageMap.values()){
  console.log(value);
}

From the looks of each iteration method, ageMap.entries() allows us to easily retrieve both the key and value while the other 2 methods only focus on retrieving the keys or the values.

Iterate with ForEach()

forEach method is similar to Map.prototype.entries() at the first glance since it can also easily retrieve key and value from the Map iterations. However, be careful in the argument since the ordering is swapped.

// Create a map to iterate over
const ageMap = new Map([
  ['Person1', 11],
  ['Person2', 33],
  ['Person3', 44], 
  ['Person4', 66],
  [10000001, 11]
]);

// Use forEach to loop through Map
ageMap.forEach(function(value, key){
  console.log(`${key} = ${value}`);
});

Conclusion

We have look into the 3 methods to iterate through a Javascript Map. Depends on the use case, we may choose any one of them.

Pre ES6 style should only be use if you are supporting older browsers. But with the help of transpiler like babel, we can use For...of or ForEach to iterate through Maps.

Show Comments

No Responses Yet

Leave a Reply