Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spread an array of objects into a parent object

Tags:

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?

like image 396
joshfarrant Avatar asked Nov 28 '16 15:11

joshfarrant


People also ask

Can you spread an array into an object?

Use the spread syntax (...) to convert an array to an object, e.g. const obj = {... arr} . The spread syntax will unpack the values of the array into a new object, where the indexes of the array are the object's keys and the elements in the array - the object's values. Copied!

What happens when you spread an array?

The spread syntax takes your array and expands it into elements.

Does spread operator work on arrays?

The spread operator unpacks elements of iterable objects such as arrays, sets, and maps into a list. The rest paramter is also denoted by three dots (…). However, it packs the remaining arguments of a function into an array. The spread operator can be used to clone an iterable object or merge iterable objects into one.

Can you spread objects in JavaScript?

Spread syntax (also known as the Spread Operator) is used to copy the enumerable properties of an object to create a clone of it. We can also update an object or merge with another object using the spread syntax.


1 Answers

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)
like image 166
Nenad Vracar Avatar answered Oct 12 '22 18:10

Nenad Vracar