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"},...];
HiddenMarkow
  • 603
  • 1
  • 7
  • 19

2 Answers2

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)
prasanth
  • 22,145
  • 4
  • 29
  • 53
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]
  }
});
Samuli Hakoniemi
  • 18,740
  • 1
  • 61
  • 74
  • Don't use [`Object.entries`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) as it is *not* ES6 but still only a draft. – str Apr 26 '17 at 08:19
  • [*Object.entries*](https://tc39.github.io/ecma262/#sec-object.entries) is ECMAScript 2018 (as str says, still a draft). By "ES6" I guess you mean ECMAScript 2015 aka [*ECMA–262 ed 6*](http://ecma-international.org/ecma-262/6.0/index.html). – RobG Apr 26 '17 at 08:31
  • Thanks for the clarification. I won't edit the post to keep your comments valid. – Samuli Hakoniemi Apr 26 '17 at 08:32