1

Is there any way to convert below array:

[
  {x: 1},
  {y: 2}
]

to this object:

{
  x: 1,
  y: 2
}

using destructuring in javascript?

I tried different patterns with no luck.

  • Hello, I am also new with Js and this is my solution: `a.forEach((obj)=>{Object.keys(obj).forEach((key)=>{b[key]=obj[key]})})` – Peterlits Zo Jul 12 '20 at 07:54

1 Answers1

0

One option is to use Array#reduce as follows:

const array = [
  {x: 1},
  {y: 2}
]

const object = array.reduce((target, item) => {
  
  // Use spread to merge current array item object 
  // into target object
  return { ...target, ...item }
}, {})

console.log(object);

The idea here is to iterate each item of your input array via the reduction and, for each iteration, merge the current array item into the target object (which will be the resulting object of the operation).

Note the order that target and item are spread into the result of the reduction; if any keys conflict during the merge of item and target, the values from item will be used.

Dacre Denny
  • 29,664
  • 5
  • 45
  • 65