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?


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);
链接地址: http://www.djcxy.com/p/38814.html

上一篇: 为什么属性必须是Python中的类属性?

下一篇: {... object,property:value}如何与扩展语法一起工作?