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.
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.
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.