How to convert Map to array of object?
You can also simply iterate over the Map
object using any compatible iteration method and add each item as an object to the resulting array.
For example, you can use Map.prototype.forEach()
in the following way:
const myMap = new Map().set('a', 1).set('b', 2);
const arr = [];
myMap.forEach((value, name) => arr.push({ name, value }));
console.log(arr);
Or, as an alternative, you may use the for...of
loop like so:
const myMap = new Map().set('a', 1).set('b', 2);
const arr = [];
for (const [name, value] of myMap) {
arr.push({ name, value });
}
console.log(arr);
Wrote a blog post explaining different methods for those who're interested in learning more.
with spread of ES6 like this:
let myMap = new Map().set('a', 1).set('b', 2);
const result = Array.from(myMap).map(([name, value]) => ({name, value}))
console.log(result);
Use Spread syntax and Array.map():
let myMap = new Map().set('a', 1).set('b', 2);
const arr = [...myMap].map(([name, value]) => ({ name, value }));
console.log(arr);
You could take Array.from
and map the key/value pairs.
let map = new Map().set('a', 1).set('b', 2),
array = Array.from(map, ([name, value]) => ({ name, value }));
console.log(array);