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:
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.
Syntax:
let Array = [...value];
// Arrow function
Array.map((e) => e);
Array.map((e, i) => {i,e});
Example: This example illustrates the implementation of the Spread Operator (…) Method and Array map() Method.
Javascript
const mapObj = new Map(); mapObj.set(1, 'abc' ); mapObj.set(2, 'xyz' ); mapObj.set(3, 'pqr' ); // Return the map console.log(mapObj); let arr = [...mapObj].map((e) => e) // Return the array console.log(arr); |
Map(3) { 1 => 'abc', 2 => 'xyz', 3 => 'pqr' } [ [ 1, 'abc' ], [ 2, 'xyz' ], [ 3, 'pqr' ] ]
Approach 2: Using Array.from() Method
The Array.from() Method returns a new instance of an array from the object provided in the arguments.
Syntax:
Array.from(object, mapFunction, thisValue);
Example: In this example, we will pass a map object and a function into Array.from() Method to convert it into an array.
Javascript
const mapObj = new Map(); mapObj.set(1, 'abc' ); mapObj.set(2, 'xyz' ); mapObj.set(3, 'pqr' ); // Return the map console.log(mapObj); // Return the array let arr = Array.from(mapObj); console.log(arr); |
Map(3) { 1 => 'abc', 2 => 'xyz', 3 => 'pqr' } [ [ 1, 'abc' ], [ 2, 'xyz' ], [ 3, 'pqr' ] ]
Approach 3: Using Map.forEach() Method
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.