How to iterate a Map using JavaScript


Borislav Hadzhiev

Thu Oct 28 20213 min read

Iterate through a Map using JavaScript #

Use the forEach() method to iterate over a Map object. The forEach method takes a function that gets invoked for each key/value pair in the Map, in insertion order. The function gets passed the value, key and the Map object on each iteration.

const map1 = new Map([ ['country', 'Chile'], ['age', 30], ]); // 👇️ Using forEach map1.forEach((value, key) => { console.log(value, key); // 👉️ Chile country, 30 age }); // 👇️ Using for...of for (const [key, value] of map1) { console.log(key, value); // 👉️ country Chile, age 30 } // ✅ Iterate over a Map's keys for (const key of map1.keys()) { console.log(key); // 👉️ country, age } // ✅ Iterate over a Map's values for (const value of map1.values()) { console.log(value); // 👉️ Chile, 30 }

In the first example, we used the Map.forEach method to iterate over the key/value pairs in a Map.

The function we passed to the method gets called with the following 3 parameters:

  • the value of the current iteration
  • the key of the current iteration
  • the Map object that's being iterated

The forEach method returns undefined.

In our other examples, we used a for...of loop.

The loop allows us to iterate over iterable objects like Maps, Sets and arrays.

We used destructuring assignment to assign the key and value variables.

const [key, value] = ['country', 'Chile']; console.log(key); // 👉️ country console.log(value); // 👉️ Chile

The for...of loop might be your preferred approach if you have to use the break keyword to exit the loop prematurely. Using the break keyword is not supported in the forEach method.

The for...of loop iterates only over an object's own properties, as opposed to the loop which also iterates over inherited properties.

In our 3rd and 4th examples, we used the Map.keys() and Map.values() methods to get iterable objects that contain the keys and values of the Map.

Note that the return values from the Map.keys() and Map.values() methods are not arrays, they are iterator objects.

If you want to convert the values to an array, e.g. to use the forEach method, you can use the Array.from method.

const map1 = new Map([ ['country', 'Chile'], ['age', 30], ]); // 👇️️ ['country, 'age'] const keys = Array.from(map1.keys()); // 👇️️ ['Chile', 30] const values = Array.from(map1.values());

An alternative approach is to use the spread operator (...) to unpack the values from the iterator object into an array.

const map1 = new Map([ ['country', 'Chile'], ['age', 30], ]); const keys = [...map1.keys()]; // 👉️ ['country, 'age'] const values = [...map1.values()]; // 👉️ ['Chile', 30]

This last 2 examples achieve the same goal. They both convert the iterator objects into an array.

You can now use the forEach method to iterate over the arrays, as well as any other array methods.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.