4

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?

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

Comments

5

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>');

2 Comments

I meant to do this but then wrote something else entirely :D. Thanks for pointing out.
@Nina - Nice answer!
4

try

var b = [];

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.