Reputation: 11
How can I transform the following:
{
Eldoret: "900",
Nairobi: "1900"
}
into:
[
{
y:"Eldoret",
a: 900
},
{
y:"Nairobi",
a:1900
}
]
using JavaScript. I've tried using the following snippet but it just picks on the last property
for(var key in data3){
if(data3.hasOwnProperty(key)){
data_obj.y = key;
data_obj.a = data3[key];
}
Output:
{
y: "Nairobi",
a: "1900"
}
Upvotes: 0
Views: 65
Reputation: 3920
You can build up the result step-by-step by appending items to a new array in your loop:
data3 = {
Eldoret: "900",
Nairobi: "1900"
}
res = []
for (var key in data3) {
res.push({
y: key,
a: data3[key],
})
}
console.log(res)
Upvotes: 0
Reputation: 53598
You iterate over your keys:
var myobj = { .... };
var objKeys = Object.keys(myobj);
var reformatted = objKeys.map(function(key) {
return {
x: key,
y: myobj[key]
};
});
Upvotes: 4