panthro
panthro

Reputation: 24099

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 = 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

Answers (2)

Curt Husting
Curt Husting

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

Madara's Ghost
Madara's Ghost

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

Related Questions