4 ms·
A shallow copy means creating a new object (or array), where all of the fields or array values point to the same references as the original: const original
by acemarke 9y ago
A shallow copy means creating a new object (or array), where all of the fields or array values point to the same references as the original:
const original = {a : {a1 : 42}, b : {b1 : 99} };
const shallowCopy = {...original};
console.log(shallowCopy.a === original.a); // true
A deep copy means creating new objects at _every_ level of nesting:
const deepCopy = _.cloneDeep(original);
console.log(deepCopy.a === original.a); // false
To properly do an immutable update for `original.a.a1`, you'd need to copy each level of nesting, and overwrite the fields in that chain:
const updated = {
...original,
a : {
...original.a,
a1 : 123
}
};
console.log(original.a === updated.a); // false
console.log(original.b === updated.b); // true