How to useMap.forEach() Method in Javascript

JavaScript map.forEach() method is used to iterate the map object and execute the callback function provided in the arguments.

Syntax:

mymap.forEach();

Example: This example illustrates the implementation of the map.forEach() Method.

Javascript




const mapObj = new Map();
mapObj.set(1, 'abc');
mapObj.set(2, 'xyz');
mapObj.set(3, 'pqr');
  
// Return the map
console.log(mapObj);
  
const arr = [];
  
mapObj.forEach(
    (value, key) => arr.push(
        { key, value }));
  
// Return the array
console.log(arr);


Output

Map(3) { 1 => 'abc', 2 => 'xyz', 3 => 'pqr' }
[
  { key: 1, value: 'abc' },
  { key: 2, value: 'xyz' },
  { key: 3, value: 'pqr' }
]

There are many inbuilt JavaScript methods that can be used to transform data from one data type to another. Above mentioned are a few of those that can be easily implemented to convert the Map object to an array.



Map to Array in JavaScript

In this article, we will convert a Map object to an Array in JavaScript. A Map is a collection of key-value pairs linked with each other. The following are the approaches to Map to Array conversion:

Similar Reads

Methods to convert Map to Array

Using Spread Operator (…) and Array map() Method Using Array.from() Method Using Map.forEach() Method...

Approach 1: Using Spread Operator (…) and Array map() Method

Using the Spread operator(…) and map() method, we can take each entry and convert it into an array of key-value pairs....

Approach 2: Using Array.from() Method

...

Approach 3: Using Map.forEach() Method

The Array.from() Method returns a new instance of an array from the object provided in the arguments....