Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Map to array of object?

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",    } ] 
like image 926
Nikhil Shrestha Avatar asked Jun 27 '19 17:06

Nikhil Shrestha


People also ask

Can I use map on an array of objects?

map() can be used to iterate through objects in an array and, in a similar fashion to traditional arrays, modify the content of each individual object and return a new array.

Can we convert map to object in JavaScript?

To convert a Map to an object, call the Object. fromEntries() method passing it the Map as a parameter, e.g. const obj = Object. fromEntries(map) . The Object.

How do you turn an object into an array?

To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .


1 Answers

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);
like image 63
Nina Scholz Avatar answered Sep 29 '22 13:09

Nina Scholz