简体   繁体   中英

es6 spread operator not combining keyed objects

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM