EN
JavaScript - convert Map to array of objects
0 points
In this article, we would like to show you how to convert a Map to an array of objects in JavaScript.
Quick solution:
xxxxxxxxxx
1
const arrayFromMap = Array.from(myMap, ([key, value]) => ({ key, value }));
In this example, we use the Array.from()
method to map the key/value pairs from the Map object into an array.
xxxxxxxxxx
1
const myMap = new Map([
2
[1, 'A'],
3
[2, 'B'],
4
[3, 'C'],
5
]);
6
7
const myArray = Array.from(myMap, ([key, value]) => ({ key, value }));
8
9
console.log(JSON.stringify(myArray, null, 4));
Output:
xxxxxxxxxx
1
[
2
{ key: 1, value: 'A' },
3
{ key: 2, value: 'B' },
4
{ key: 3, value: 'C' }
5
]