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} ]
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} ]
Share
Improve this question
edited Mar 19, 2020 at 16:38
YanetP1988
1,3564 gold badges19 silver badges44 bronze badges
asked Feb 13, 2017 at 4:50
vishnuvishnu
791 gold badge1 silver badge3 bronze badges
0
4 Answers
Reset to default 8You can use forEach
callback on Map
var res = [];
map.forEach(function(val, key) {
res.push({ region: key, value: val });
});
You can use for ... in
to iterate over the keys of an object (map). Also, it looks like your object has properties that start with a dollar sign and your desired result has those stripped out. You can use substring
to do that.
var a = [];
for (var k in map) {
a.push({region:k.substring(1), value:map[k]});
}
This should do it:
// Create the map
let locationsMap = new Map();
locationsMap.set('$Central', 265045);
locationsMap.set('$East', 178576);
locationsMap.set('$South', 103926);
locationsMap.set('$West', 272264);
// Convert the map to an array of objects
let locationsArray = Array.from(locationsMap, item => ({[item[0]]: item[1]}))
Use for..in loop to iterate the Map object and push the items in array. Inside for..in loop create an object with properties region and value, push this object into an array.
<!DOCTYPE html>
<html>
<head>
<title>For in example</title>
<script type="text/javascript">
var map = {
"$Central": 265045,
"$East" : 178576,
"$South" : 103926,
"$West" : 272264
};
var arr = [];
for (var prop in map) {
var item = {region : prop.substring(1), value:map[prop]};
arr.push(item);
}
console.log('Map Object --> ',map);
console.log('Array of objects --> ',arr);
</script>
</head>
<body>
</body>
</html>