Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does {...object, property: value} work with spread syntax?

When reviewing the ES6 docs, I noted that it is recommended to use the spread syntax over the more verbose Object.assign() method. But, I am a bit confused as to how this is being accomplished.

Is object in this case being broken down to key: value pairs, after which the property on the right of the comma is either added or overwritten, and finally being reassembled?

like image 683
toolshed Avatar asked Apr 03 '17 07:04

toolshed


1 Answers

Is object in this case being broken down to key: value pairs, after which the property on the right of the comma is either added or overwritten, and finally being reassembled?

The key-value pairs of the original object object are actually being used in combination (merging) with the new object which has an extra property var2( they are getting combined to newObject).

You can think of it as object is becoming a subset of newObject in the place where the spread syntax in being used, while properties with same key are being overridden.

Check the below example:

const object = { txt: 'Test' };
const newObject = {...object, var2: 'aa' };

// logs Object {txt: "Test", var2: "aa"}
console.log(newObject);

const object2 = { txt: 'Test' };
const newObject2 = {...object, txt: 'Test2', var2: 'aa' };

// Object {txt: "Test2", var2: "aa"}
console.log(newObject2);

// merging all objects to a new object
var object3 = {first: 'Hello', second: 'World'};
var newObject3 = {...object, anotherVar: 'stack', ...object2, ...object3};

// Object {txt: "Test", anotherVar: "stack", first: "Hello", second: "World"}
console.log(newObject3);
like image 166
KAD Avatar answered Sep 28 '22 05:09

KAD