Reputation: 1540
i'm trying to convert a Map into array of object
Lets say I have the following map:
let myMap = new Map().set('a', 1).set('b', 2);
And I want to convert the above map into the following:
[
{
"name": "a",
"value": "1",
},
{
"name": "b",
"value": "2",
}
]
Upvotes: 125
Views: 226226
Reputation: 718
let map = new Map().set('a', 1).set('b', 2),
array = Array.from(map.values());
console.log(array);
Upvotes: 7
Reputation: 11
You'll got : [ { key: 'a', value: 1 }, { key: 'b', value: 2 } ]
if instead, you use the following line :
const arr = [...map ].map(([key, value]) => ([key]: value}));
You will have the following result : [ {a: 1}, {b: 2} ]
Upvotes: -1
Reputation: 8835
Very simple I will explain in steps:
const map = new Map().set('a', 1).set('b', 2).set('c', 3)
const mapArr = [...map] // array of arrays
key
-value
pairs. map
function returns a new array containing object
of key
-value
pairs.const arr = mapArr.map(([key, value]) => ({key, value}))
** Remember: ** the name we use for mapping the data will be the name of the object mapped in this case key
and value
.
One liner:
const map = new Map().set('a', 1).set('b', 2).set('c', 3)
const arr = [...map ].map(([key, value]) => ({key, value}))
console.log({arr})
Upvotes: 5
Reputation: 27
With ES6 Spread syntax only :
const myMap = new Map().set('a', 1).set('b', 2);
const arr = [...myMap];
console.log(arr);
Upvotes: 0
Reputation: 12954
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);
Upvotes: 58
Reputation: 4806
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);
Upvotes: 10
Reputation: 386522
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);
Upvotes: 199