How to Convert a Map to an Array of Objects using JavaScript?

To convert a map to an array of objects, you can use the Array.from() method. The Array.from() method creates an array from an iterable. And It can take one, two, or three parameters at a time.

The first parameter is the iterable object which in our case would be the map. And the second parameter can be any mapping function which is called on every element of the iterable.

Array.from(iterable, mappingFun);

In our case, we are using an arrow function as a mapping function, which will be called on each map item and will return an object containing the current key-value pair.

See the implementation below:

const map = new Map();

map.set('name', 'John');
map.set('age', 24);

const arr = Array.from(map, ([key, val])=>{
   return {[key]: val} 
});

console.log(arr);
// 👉 Output: [ { name: 'John' }, { age: 24 } ]

Convert a Map to an Array of Objects using forEach() Loop

An alternative approach could be to iterate over each map item using a forEach loop and simply pushing the current key-value pair into the array. This will also give you the desired result.

This is how you can do it:

const map = new Map();

map.set('name', 'John');
map.set('age', 24);

const arr = [];
map.forEach((val, key)=>{
   arr.push({
       [key]: val
   }) 
});

console.log(arr);
// 👉 Output: [ { name: 'John' }, { age: 24 } ]

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.