Making Changes To A Copied Array, Updates The Original?
I have an array of objects: let users = [{name: 'john', address: '10 king street'}, ....]; I copy this array via: let usersCopy = users.slice(0); Then if I do usersCopy[0].name
Solution 1:
That's because [].slice()
does a shallow copy, meaning you get a new array, but it doesn't clone the objects underneath. Therefore, users[0] === usersCopy[0]
, as they are the same reference to the same object.
You will need to replace usersCopy[0]
entirely. For example:
usersCopy[0] = {...usersCopy[0], name: 'jeff'}
Which would create a new object with everything from usersCopy[0]
shallow-copied into it.
Solution 2:
Edit: As noted below this answer is not correct
Here's an alternate way to create a separate array from the original so you can modify the clone
const users = [{name: 'John', address: '10 king street'}];
const clone = newArray(users);
clone[0].name = 'Jeff';
console.log(clone[0].name) //jeffconsole.log(users[0].name) //john
Post a Comment for "Making Changes To A Copied Array, Updates The Original?"