‘a’ array wasn’t affected.
const a = [1,2,3]
const b = [...a] // shallow copy
b[0] = 9
console.log(a) // [1,2,3]
console.log(b) // [9,2,3] results as expected
----------
const a = [{name:"John"},{name:"George"}];
const b = [...a];
b[0] = {name:"Oliver"}
console.log(a) // [ { name: 'John' }, { name: 'George' } ]
console.log(b); // [ { name: 'Oliver' }, { name: 'George' } ] results as expected
----------
const a = [{name:"John"},{name:"George"}];
const b = [...a];
b[0].age = 21
console.log(a); //[ { name: 'John', age: 21 }, { name: 'George' } ]
console.log(b); // [ { name: 'John', age: 21 }, { name: 'George' } ]
// why were affected ‘a’ array ?
Why were they both affected? It shows the same reference, but in the other 2 examples above, there was no change, only the ‘b’ array changed.
2
Answers
It happens because the reference of the object is not changing, internally when you make a shallow copy of the "a" array, you are making a copy of a reference to those objects, so after changing b[0] object you are also affecting a[0] since its the same object
In the second example, you assigned
b[0]
to totally new object ( with new referance ), but in the third example, you changed theage
in the object with reference shared between botha
andb
arrays.If you need the same behavior you need to map new references.
Here
[...a.map(o => ({...o}))]
will replace all the objects insidea
array with a new copy but with a different reference.Update
Or as shared by @Andy and @Amadan, you can use
structuredClone
to deep clone the array.