Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion of data format from a single object to an array of objects of key value pairs

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?

like image 603
Deadpool Avatar asked Dec 07 '22 23:12

Deadpool


2 Answers

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

like image 103
Nikhil Aggarwal Avatar answered Dec 11 '22 10:12

Nikhil Aggarwal


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>');
like image 44
Nina Scholz Avatar answered Dec 11 '22 12:12

Nina Scholz