Converting a data format from one object to an array of objects of a pair of key values

I have data in one object as json-format:

var a = {
    "1": "alpha",
    "2": "beta",
    "3": "ceta"
}

I want to convert it to the following format:

var b = [
    {id: 1, label: "alpha"},
    {id: 2, label: "beta"},
    {id: 3, label: "ceta"}
];

Can anyone suggest a way to do this?

+4
source share
3 answers

You can try to run

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);
Run codeHide result

Pay attention . You need to update your object a. Missing commas.

+5
source

There are Object.keys()and in this sentence 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>');
Run codeHide result
+5
source

var b = [];

for ( var key in a )
{
   b.push( { id : key, label :a[key] } );
}
console.log(b);
+4

Source: https://habr.com/ru/post/1629886/


All Articles