0

I want to build an object of keyed objects.

Why is the spread operator not combining as used below? Instead it only keeps the second object.

let a = {
  key1: {
    floo: 'blar'
  }
}

let b = {
  key2: {
    floo: 'blar'
  }
}
console.log(...a, b);

And most importantly please show me the correct way to do this!

Thanks

Jesse
  • 3,522
  • 6
  • 25
  • 40
yak
  • 340
  • 3
  • 7

1 Answers1

3

It should be

console.log({...a, ...b});

The above will merge the two objects and will create a new object with key1 an key2 respectively. Also, note that spread operator for objects doesn't work the same way as Object.assign() does.

Note that the merged object is just a reference. For example, modifying the value of the object like

a.key1.floo = 'someotherval';

will alter the a object and also reflect in the merged object.

For more information, refer to Spread in Object Literals section.

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278