Reputation: 732
I have a Javascript Object :
{
"Central":73322346.47533998,
"East":87801368.39711998,
"North":76468694.37534,
"South":142687496.66816995,
"West":76815749.40554999
}
I want to map this object into an array that look like this
[
{"name" :"Central ,"size" : 73322346.47533998},
{"name" : "East", "size" : 87801368.39711998},
{"name": "North","size":76468694.37534},
{"name": "South","size" :142687496.66816995},
{"name":"West","size":76815749.40554999}
]
How do I go about?
Upvotes: 0
Views: 225
Reputation: 4175
In ES2017 you can do:
Object.entries(obj).map(([name, size])=> ({name, size}))
var obj = {
"Central":73322346.47533998,
"East":87801368.39711998,
"North":76468694.37534,
"South":142687496.66816995,
"West":76815749.40554999
}
var res = Object.entries(obj).map(([name, size])=> ({name, size}));
console.log(res);
In ES2011 (5.1), ES2015 (6),.... and onward you can do:
Object.keys(obj).map(function(k) {
return {name: k, size: obj[k]}
})
var obj = {
"Central":73322346.47533998,
"East":87801368.39711998,
"North":76468694.37534,
"South":142687496.66816995,
"West":76815749.40554999
}
var res = Object.keys(obj).map(function(k) {
return {name: k, size: obj[k]}
})
console.log(res)
Upvotes: 2
Reputation: 20361
A simple way to do this is to interate over the keys of the input object using a for..in loop:
const input = {
"Central": 73322346.47533998,
"East": 87801368.39711998,
"North": 76468694.37534,
"South": 142687496.66816995,
"West": 76815749.40554999
};
let output = [];
for (const key in input)
{
output.push({ "name": key, "size": input[key] });
}
console.log(output);
This is probably the fastest way to achieve the desired output.
Upvotes: 0
Reputation: 30739
You can loop over the key
s of the object to get the array of objects as expected:
var data = {"Central":73322346.47533998,"East":87801368.39711998,"North":76468694.37534,"South":142687496.66816995,"West":76815749.40554999};
var res = [];
Object.keys(data).forEach((key)=>{
res.push({
name: key,
size: data[key]
});
});
console.log(res);
Upvotes: 1
Reputation: 1546
do like this:
obj = {"Central":73322346.47533998,"East":87801368.39711998,"North":76468694.37534,"South":142687496.66816995,"West":76815749.40554999}
out = [];
Object.keys(obj).forEach(function(d){ out.push({name: d, size: obj[d]});})
//out will contain your formatted data
Upvotes: 3