Distributing an array of objects to a parent object

Is there an easy way to use the spread operator ...to combine an array of objects with another object to create one object? This example shows what I'm trying to do:

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

const obj = {
  hello: 'world'
};

The result I'm looking for is as follows:

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

I tried, among other things, the following, but this does not quite give the expected result.

{
  hello: 'world'
  ...arrayOfObjects
}

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

Can this be done with the smart use of the spread operator?

+4
source share
2 answers

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

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

const obj = {
  hello: 'world'
};

var result = Object.assign({}, obj, ...arrayOfObjects);
console.log(result)
Run codeHide result
+11
source

U can use Object.assign ();

Object.assign(obj, ...arrayOfObjects)

This option will mutate the obj object instead of creating a new instance.

+2
source

Source: https://habr.com/ru/post/1662159/


All Articles