ES6 objects destructuring assignment (VS shallow copy deep copy)

Extended operator object (...) for all parameters extracted through both the attributes of the object, copy into the current object.

Copy of the object

let aa = {
    age: 18,
    name: 'aaa'
}

 
let bb = {...aa};
console.log(bb);  // {age: 18, name: "aaa"}

Merge objects

Extended operator (...) can be used to combine two objects

let aa = {
    age: 18,
    name: 'aaa'
} 

let bb = {
    sex: '男'
}
  
let cc = {...aa, ...bb}; 


// 等同于: 
// let cc = Object.assign({}, aa, bb);


console.log(cc); // {age: 18, name: "aaa", sex: "男"}

Copy and modify objects

Later extended operator, together with custom properties, the extended attributes with the same name inside the operator will be overwritten.

let aa = {
    age: 18,
    name: 'aaa'
}
 
let dd = {...aa, name: 'ddd'};
 

// 等同于: 
// let dd = {...aa, ...{name: 'ddd'}};
// let dd = Object.assign({}, aa, { name: 'ddd'});



console.log(dd); // {age: 18, name: "ddd"}

Generally, when the modified state in the redux, the assignment will use the method of deconstruction.

However, the new object is obtained after deconstruction, as opposed to the old object is a shallow copy or a deep copy?

For example, the following must be assigned by reference:

let aa = {
    age: 18,
    name: 'aaa'
}

let bb = aa;
bb.age = 22;

console.log(aa.age); // 22

Above, the object is a reference to aa bb assignment. So, if you use destructuring assignment to get bb:

let aa = {
    age: 18,
    name: 'aaa'
}

let bb = {...aa};
bb.age = 22;

console.log(aa.age); // 18
  • Seen, changing the value of the attribute bb of age and not change the value of the age attribute aa of an object, therefore, the above example is a copy-aa bb
  • However, this copy is shallow copy only one layer, or a deep copy?
let aa = {
    age: 18,
    name: 'aaa',
    address: {
        city: 'shanghai'
    }
}

let bb = {...aa};
bb.address.city = 'shenzhen';

console.log(aa.address.city);  // shenzhen

Visible, aa bb destructuring assignment to the new object, only one was shallow copy, bb reference object attributes (address) of the property (city), or the object attribute in the attribute aa.

If, as the copy attribute aa of the city, can be treated as follows:

let aa = {
    age: 18,
    name: 'aaa',
    address: {
        city: 'shanghai'
    }
}

let bb = {
    ...aa,
    address: {...aa.address}
};

bb.address.city = 'shenzhen';

console.log(aa.address.city);  // shanghai

Guess you like

Origin www.cnblogs.com/cckui/p/11518842.html