Jan
Jan

Reputation: 3401

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)

Upvotes: 2

Views: 1296

Answers (2)

Ori Drori
Ori Drori

Reputation: 191936

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.

Upvotes: 3

Christopher Chiche
Christopher Chiche

Reputation: 15325

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

Upvotes: 2

Related Questions