Abhijeet Abhijeet - 5 months ago 6
JSON Question

Merge Json Array to an Object

I have an array containing objects like

[
{
"name": "foo",
"value": "bar"
},
{
"name": "foo1",
"value": "bar1"
}
]


and I want something like

{"foo":"bar","foo1":"bar1"}


Can someone please help me out with this ?

Answer

Just do a reduce with Object.assign

var arr = [
  {
   "name": "foo",
   "value": "bar"
   },
   {
    "name": "foo1",
    "value": "bar1"
   }
];

var arr2 = arr.reduce((z, {name,value})=>
  Object.assign(z, {[name]: value}), {});

console.log(arr2);


Here's the ES5 version

var arr = [
  {
   "name": "foo",
   "value": "bar"
   },
   {
    "name": "foo1",
    "value": "bar1"
   }
];

var arr2 = arr.reduce(function(a,b) {
  a[b.name] = b.value;
  return a;
}, {});

console.log(arr2);