Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a map object to array of objects in Java script

I am new to JS.

I have a map object.

 Map {$Central: 265045, $East: 178576, $South: 103926, $West: 272264}

I would like to convert it into an array of objects

 [ {region:"Central", value: 265045}, {region:"East", value: 178576},
 {region:"South", value: 103926}, {region:"West", value: 272264} ]
like image 213
vishnu Avatar asked Feb 13 '17 04:02

vishnu


People also ask

How do you map data from an array of objects in JavaScript?

The syntax for the map() method is as follows: arr. map(function(element, index, array){ }, this); The callback function() is called on each array element, and the map() method always passes the current element , the index of the current element, and the whole array object to it.

Can you make an array of objects in JavaScript?

Creating an array of objectsWe can represent it as an array this way: let cars = [ { "color": "purple", "type": "minivan", "registration": new Date('2017-01-03'), "capacity": 7 }, { "color": "red", "type": "station wagon", "registration": new Date('2018-03-03'), "capacity": 5 }, { ... }, ... ]


1 Answers

You can use forEach callback on Map

var res = [];
map.forEach(function(val, key) {
    res.push({ region: key, value: val });
});
like image 86
JohanP Avatar answered Sep 16 '22 22:09

JohanP