joshfarrant joshfarrant - 5 days ago 6
Javascript Question

Spread an array of objects into a parent object

Is there a simple way to use the spread

...
operator to combine an array of objects with a another object to create a single object? This example shows what I'm trying to accomplish:

const arrayOfObjects = [
{ x: 'foo' },
{ y: 'bar' }
];

const obj = {
hello: 'world'
};


The output I'm looking for is as follows:

{
x: 'foo',
y: 'bar',
hello: 'world'
}


I've tried the following, amongst other things, but it doesn't quite give the intended output.

{
hello: 'world'
...arrayOfObjects
}

// Gives
{
0: { x: 'foo' },
1: { y: 'bar' },
hello: 'world'
};


Is it possible to do this with clever use of the spread operator?

Answer

You can use Object.assign() with spread syntax ...

const arrayOfObjects = [{
  x: 'foo'
}, {
  y: 'bar'
}];

const obj = {
  hello: 'world'
};

var result = Object.assign({}, obj, ...arrayOfObjects);
console.log(result)

Comments