简体   繁体   中英

Spread operator equivalent of Object assign

What would be the equivalent of merging these objects to a spread operator? I wanna use spread instead of assign in my redux app.

return Object.assign({}, obj1, obj2)

The equivalent would be:

return { ..obj1, ...obj2 };

However this won't work without transpiling (by babel for example), as object rest spread is a stage-3 recommendation, and not supported by current browsers. If you use babel, you'll have to use the Object rest spread transform babel plugin or the babel stage-3 preset .

As explained in the docs :

Note: Typically the spread operators in ES6 goes one level deep while copying an array. Therefore, they are unsuitable for copying multidimensional arrays. It's the same case with Object.assign and Object spread operators. Look at the example below for a better understanding.

This means that the spread is made in anew object, so no need to pass an empty object as is Object.assign . Hence you can just do:

return {...obj1, ...obj2}

As an additional note, here is how babel transpiles the spread operator:

const a = {...obj1, ...obj2}

becomes:

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var a = _extends({}, obj1, obj2);

See for yourself

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