How to iterate through a Map object in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 3, 2024
4 min

banner

# Table of Contents

  1. Iterate through a Map object in JavaScript
  2. Iterate over a Map in Reverse Order

# Iterate through a Map object in JavaScript

Use the Map.forEach() method to iterate through a Map object.

The forEach method takes a function that gets invoked for each key-value pair in the Map in insertion order.

index.js
const map1 = new Map([ ['country', 'Chile'], ['age', 30], ]); map1.set('name', 'bobby hadz'); map1.forEach((value, key) => { // Chile country // 30 age // bobby hadz name console.log(value, key); });

iterate through map object

The code for this article is available on GitHub

The function we passed to the Map.forEach() method gets called for each key-value pair in the Map object.

The function gets passed 3 arguments on each iteration:

  1. the value of the current iteration
  2. the key of the current iteration
  3. the Map object that is being iterated

The Map.forEach() method returns undefined.

# Iterate through a Map object using a for...of loop

Alternatively, you can use a for...of loop.

The for...of loop assigns the key and the value of the current iteration to variables.

index.js
const map1 = new Map([ ['country', 'Chile'], ['age', 30], ]); map1.set('name', 'bobby hadz'); for (const [key, value] of map1) { // country Chile // age 30 // name bobby hadz console.log(key, value); }

iterate through map object using for of

The code for this article is available on GitHub

The for...of statement is used to loop over iterable objects like arrays, strings, Map, Set and NodeList objects and generators.

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

index.js
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.

# Iterating over the Keys or Values of a Map object

This is a two-step process:

  1. Use the Map.keys() method to get an iterator object of the Map's keys.
  2. Use the Map.values() method to get an iterator object of the Map's values.
  3. Use a for...of loop to iterate over the keys or values.
index.js
const map1 = new Map([ ['country', 'Chile'], ['age', 30], ]); map1.set('name', 'bobby hadz'); for (const key of map1.keys()) { // country // age // name console.log(key); }

iterating over keys or values of map object

The code for this article is available on GitHub

If you need to iterate over the Map object's values, use the Map.values() method.

index.js
const map1 = new Map([ ['country', 'Chile'], ['age', 30], ['name', 'bobby hadz'], ]); for (const key of map1.values()) { // Chile // 30 // bobby hadz console.log(key); }

The Map.keys method returns an iterator object of the Map's keys.

index.js
const map1 = new Map([ ['country', 'Chile'], ['age', 30], ['name', 'bobby hadz'], ]); // ๐Ÿ‘‡๏ธ [Map Iterator] { 'country', 'age', 'name' } console.log(map1.keys()); // ๐Ÿ‘‡๏ธ [Map Iterator] { 'Chile', 30, 'bobby hadz' } console.log(map1.values());
The code for this article is available on GitHub

The Map.values() method returns an iterator object of the Map's values.

The for...of loop is useful when you need to exit the loop prematurely if a certain condition is met.

index.js
const map1 = new Map([ ['country', 'Chile'], ['age', 30], ['name', 'bobby hadz'], ]); for (const value of map1.values()) { console.log(value); if (value === 'Chile') { break; } }

If the condition in the if statement is met, the break statement exits the for...of loop.

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

You can use the Array.from method if you want to convert the Map's values or keys to an array, e.g. to be able to use the forEach method.

index.js
const map1 = new Map([ ['country', 'Chile'], ['age', 30], ]); // ๐Ÿ‘‡๏ธ๏ธ ['country, 'age'] const keys = Array.from(map1.keys()); // ๐Ÿ‘‡๏ธ๏ธ ['Chile', 30] const values = Array.from(map1.values());
The code for this article is available on GitHub

You can also use the spread syntax (...) to unpack the values from the iterator object into an array.

index.js
const map1 = new Map([ ['country', 'Chile'], ['age', 30], ]); const keys = [...map1.keys()]; // ๐Ÿ‘‰๏ธ ['country, 'age'] const values = [...map1.values()]; // ๐Ÿ‘‰๏ธ ['Chile', 30]

The last 2 examples achieve the same result. They both convert the iterator objects to arrays.

# Iterate over a Map in Reverse Order

To iterate over a Map in reverse order:

  1. Use the Array.from() method to convert the Map to an array.
  2. Use the reverse() method to reverse the array.
  3. Use the forEach() method to iterate over the reversed array.
index.js
const map1 = new Map([ ['one', 1], ['two', 2], ]); // ๐Ÿ‘‡๏ธ [['two', 2], ['one', 1]] const reversedArr = Array.from(map1).reverse(); reversedArr.forEach(([key, value]) => { console.log(key, value); // ๐Ÿ‘‰๏ธ two 2, one 1 });

iterate over map in reverse order

The code for this article is available on GitHub

The first step is to convert the Map to an array.

index.js
const map1 = new Map([ ['one', 1], ['two', 2], ]); // ๐Ÿ‘‡๏ธ [['one', 1], ['two', 2]] const arr = Array.from(map1);

We used the Array.reverse() method to reverse the array.

index.js
const map1 = new Map([ ['one', 1], ['two', 2], ]); // ๐Ÿ‘‡๏ธ [['one', 1], ['two', 2]] const arr = Array.from(map1); // ๐Ÿ‘‡๏ธ [['two', 2], ['one', 1]] const reversed = arr.reverse();
The code for this article is available on GitHub
The reverse() method reverses the array in place and returns the result.

You can use the Array.forEach method to iterate over the reversed array.

The function we passed to the forEach method gets called with each element of the array.

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

index.js
const [key, value] = ['one', 1]; console.log(key); // ๐Ÿ‘‰๏ธ "one" console.log(value); // ๐Ÿ‘‰๏ธ 1

You can also use the spread syntax (...) to convert the Map to an array.

index.js
const map1 = new Map([ ['one', 1], ['two', 2], ]); // ๐Ÿ‘‡๏ธ [['two', 2], ['one', 1]] const reversedArr = [...map1].reverse(); reversedArr.forEach(([key, value]) => { console.log(key, value); // ๐Ÿ‘‰๏ธ two 2, one 1 });
The code for this article is available on GitHub

This code sample achieves the same result, however, this time we used the spread syntax (...) to unpack the key-value pairs of the Map into an array.

In some very rare cases, the spread syntax (...) doesn't play nice when using TypeScript. This issue doesn't occur when using Array.from().

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev