0

I want to convert an object of key values to an array of objects in javascript

var obj={"name1":"value1","name2":"value2",...};

How can i convert it to

arr=[{"name":"name1","value":"value1"},{"name":"name2","value":"value2"},...];
0

2 Answers 2

1

Try with array#map and Array#push

var obj={"name1":"value1","name2":"value2"};
var res=[];
Object.keys(obj).map(a => res.push({name:a , value:obj[a]}))
console.log(res)

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

Comments

0

Short answer (ES6):

const arr = Object.entries(obj).map(([name, value]) => {
  return {
    name,
    value
  }
});

Another answer (ES5):

var arr = Object.keys(obj).map(function(key) {
  return {
    name: key,
    value: obj[key]
  }
});

3 Comments

Don't use Object.entries as it is not ES6 but still only a draft.
Object.entries is ECMAScript 2018 (as str says, still a draft). By "ES6" I guess you mean ECMAScript 2015 aka ECMA–262 ed 6.
Thanks for the clarification. I won't edit the post to keep your comments valid.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.