1

Suppose I have a data structure like this:

const list = [
  {"hello": "world"},
  {"goodbye": "cruel world"}
]

and I want to join it into:

{"hello": "world",
 "goodbye": "cruel world"}

I can do it semi-elegantly like so:

const union = l.reduce((acc, o) => {
  Object.keys(o).forEach((k) => acc[k] = o[k]);
  return acc;
}, {})

But is there a more elegant way, perhaps built into the JS standard library?

Philip
  • 1,532
  • 12
  • 23

1 Answers1

3

You can do this with Object.assign() and ES6 spread syntax.

const list = [
  {"hello": "world"},
  {"goodbye": "cruel world"}
]

var obj = Object.assign({}, ...list);
console.log(obj)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176