0

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 ?

1

3 Answers 3

2

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

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

Comments

1

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

3 Comments

you can just use console.log in the snippets and it will display now
@naomik Oh, it looks so great now :) I haven't been at SO for a while. Thanks a lot!
It's pretty new. Definitely something they've needed for a long time. ^_^
0
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.