Sling Academy
Home/JavaScript/How to iterate over a Map object in JavaScript

How to iterate over a Map object in JavaScript

Last updated: March 22, 2023

In JavaScript, iterating over a Map object can be useful for many tasks that involve accessing, modifying, or manipulating the key-value pairs. This practical, code-centric article will walk you through a couple of different ways to do so (some of them are variations or combinations of the others).

Using a for…of loop

You can use a for…of loop to iterate over a given Map object. The loop will iterate over each key-value pair in the Map object.

Example:

const myMap = new Map([
  ['key1', 'value1'],
  ['key2', 'value2'],
  ['key3', 'value3'],
  ['key4', 'value4'],
]);

for (const [key, value] of myMap) {
  console.log(key, '--->', value);
}

Output:

key1 ---> value1
key2 ---> value2
key3 ---> value3
key4 ---> value

Using the forEach() method

The forEach() method executes a callback function for each key-value pair in the Map object in insertion order. The callback function receives 3 arguments: the value, the key, and the Map object itself.

Example:

let map = new Map([
  ['Sling', 'Academy'],
  ['Foo', 'Bar'],
  ['Hello', 'Moon'],
]);

map.forEach((value, key, map) => {
  console.log(`key: ${key}, value: ${value}`);
});

Output:

key: Sling, value: Academy
key: Foo, value: Bar
key: Hello, value: Moon

This approach is simple and concise, but it does not allow breaking out of the loop or returning a value from the callback function. It also does not support asynchronous operations or promises.

Using the Map.keys() method

You can use the keys() method to get an iterator over the keys of the Map object, and then use some kind of loop to iterate over it. This approach is neat and useful when you don’t care about the values.

Example:

let map = new Map([
  ['a', 1],
  ['b', 2],
  ['c', 3],
]);

let keys = map.keys();

// loop over keys with a while loop
while (true) {
  let result = keys.next();
  if (result.done) break;
  console.log(result.value);
}

Output:

a
b
c

This approach is flexible and expressive, but it may require additional variables or destructuring assignments to access the key-value pairs. It also supports breaking out of the loop or returning a value from the loop body. It also supports asynchronous operations with async/await.

Using the Map.values() method

Similar to the previous method and having the same advantages, but instead of getting keys, this approache calls the values() method to get an iterator over the values of the Map object.

Example:

const map = new Map([
  ['b', 'blue'],
  ['r', 'red'],
  ['g', 'green'],
]);

let values = map.values();
for (let value of values) {
  console.log(`value: ${value}`);
}

Output:

value: blue
value: red
value: green

Using the Array.from() function

You can use the Array.from() function to convert a Map object or its iterator to an array, and then use a for loop or Array methods such as forEach(), map(), filter(), etc.

Example:

let myMap = new Map([
  ['I', 1],
  ['II', 2],
  ['III', 3],
  ['IV', 4],
  ['V', 5],
]);

let arr = Array.from(myMap);
arr.map(([key, value]) => console.log(`${key} --> ${value}`));

Output:

I --> 1
II --> 2
III --> 3
IV --> 4
V --> 5

This technique is versatile and powerful, but it may also cause losing some information or functionality of the Map object, such as insertion order, non-string keys, etc. It also creates an extra array that may consume memory space and affect performance.

Next Article: JavaScript: Add/Remove Key-Value Pairs to/from a Map

Previous Article: How to create a Map object in JavaScript

Series: Modern Data Structures in JavaScript

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration