Spread an array of objects into a parent object

Object.assign is great, I came up with another possible solution using reduce for who like using it


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

const obj = {
  hello: 'world'
};

let result = arrayOfObjects.reduce((prev, current) => ({
        ...prev,
        ...current
    }), obj)

console.log(result);
// {hello: "world", x: "foo", y: "bar"}

U can use Object.assign();

Object.assign(obj, ...arrayOfObjects)

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


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)

Tags:

Javascript