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} ]
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.
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 }, { ... }, ... ]
You can use forEach
callback on Map
var res = [];
map.forEach(function(val, key) {
res.push({ region: key, value: val });
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With