Abhijeet Ahuja
Abhijeet Ahuja

Reputation: 5950

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 ?

Upvotes: 0

Views: 83

Answers (3)

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

You can simply iterate through the array and build your object property-by-property.
It can be done easier with Array.prototype.forEach:

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

var o = {};

arr.forEach(function(x) {
  o[x.name] = x.value;
});

console.log(o);

Upvotes: 1

Mulan
Mulan

Reputation: 135217

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

Upvotes: 2

Nikhil Dev
Nikhil Dev

Reputation: 126

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

let myObject = {}
for (let item of items) {
  myObject[item.name] = item.value;
}

console.log(myObject);

Please note that this is in es6.

Upvotes: 0

Related Questions