I have a data in a single object as json-format:
var a = {
"1": "alpha",
"2": "beta",
"3": "ceta"
}
I want to convert it into the following format:
var b = [
{id: 1, label: "alpha"},
{id: 2, label: "beta"},
{id: 3, label: "ceta"}
];
Can someone suggest a way to do this?
You can try following
var a = {
"1": "alpha",
"2": "beta",
"3": "ceta"
}
var b = [];
for (var key in a) {
if (a.hasOwnProperty(key)) {
b.push({
"id": key,
"label": a[key]
});
}
}
console.dir(b);
Please note - You need to update your object a
- Commas are missing
This proposal features Object.keys()
and Array#map()
.
var a = { "1": "alpha", "2": "beta", "3": "ceta" },
b = Object.keys(a).map(function (k) {
return { id: k, label: a[k] };
});
document.write('<pre>' + JSON.stringify(b, 0, 4) + '</pre>');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With