1

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
panthro
  • 22,779
  • 66
  • 183
  • 324
  • 1
    Possible duplicate of [Why does changing an Array in JavaScript affect copies of the array?](https://stackoverflow.com/questions/6612385/why-does-changing-an-array-in-javascript-affect-copies-of-the-array) – Peter B Jan 30 '18 at 19:50
  • But Im changing the copy not the original. – panthro Jan 30 '18 at 19:50
  • Like said in the "duplicate", this is a "shallow copy". In your array, you got another object (a json) who won't be cloned. – One More Light Jan 30 '18 at 19:53
  • The duplicate talks about assigning the same array to a different variable, this is a different question. – Madara's Ghost Jan 30 '18 at 19:53

2 Answers2

3

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.

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
  • How can I not shallow copy the objects in the array? – panthro Jan 30 '18 at 19:55
  • 1
    You could use lodash's `_.cloneDeep` or some other method of deep cloning. But generally speaking, you should avoid deep cloning arbitrary objects, as it's rather expensive in terms of performance. – Madara's Ghost Jan 30 '18 at 21:00
1

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
Curt Husting
  • 248
  • 2
  • 8
  • `clone` is now a nested array, with an additional property `name` which is equal to `Jeff`, if you try to log `clone[0].address` you'll see that it's undefined. – Madara's Ghost Jan 30 '18 at 20:54