Reputation: 24099
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 = jeff;
It also updated this on the original users array:
console.log(usersCopy[0].name) //jeff
console.log(users[0].name) //jeff
I'm expecting to see:
console.log(usersCopy[0].name) //jeff
console.log(users[0].name) //john
Upvotes: 1
Views: 188
Reputation: 248
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 = new Array(users);
clone[0].name = 'Jeff';
console.log(clone[0].name) //jeff
console.log(users[0].name) //john
Upvotes: 1
Reputation: 175088
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.
Upvotes: 3