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); |
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: