5

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

4 Answers 4

8

You can use forEach callback on Map

var res = [];
map.forEach(function(val, key) {
    res.push({ region: key, value: val });
});
Sign up to request clarification or add additional context in comments.

Comments

5

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

Comments

4

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

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.