vishnu
vishnu

Reputation: 79

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} ]

Upvotes: 5

Views: 13887

Answers (4)

Jack Vial
Jack Vial

Reputation: 2474

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]}))

Upvotes: 4

dana
dana

Reputation: 18155

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]});
}

Upvotes: 5

Pooja Kedar
Pooja Kedar

Reputation: 437

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>

Upvotes: 1

JohanP
JohanP

Reputation: 5472

You can use forEach callback on Map

var res = [];
map.forEach(function(val, key) {
    res.push({ region: key, value: val });
});

Upvotes: 8

Related Questions