2 ms·
What's a nested shallow copy, and how is it different from a deep copy ?
by littlestymaar 9y ago
What's a nested shallow copy, and how is it different from a deep copy ?
- acemarke 9y agoA 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