4

I have two array called 'persons' and 'persons2', The 'persons2' array would to be copy of 'persons' array, But the problem is when I copy it, and I want to change the second array, the first array is also changing. This is my code:

  export class AppComponent {

  persons = [
    {
      name:'David',
      lname:'Jeu'
    }
  ];

  persons2=[...this.persons];

  constructor(){
      console.log(this.persons[0]);
      this.persons2[0].name='Drake';
      console.log(this.persons[0]);

      console.log(this.persons2[0]);
  }

}
Jack
  • 89
  • 3
  • 12

3 Answers3

8

But the problem is when I copy it, and I want to change the second array, the first array is also changing

That is because the objects inside both the arrays are sharing same reference. To perform a deep copy try the following :

let persons2 = person.map(x => Object.assign({}, x));

Or

let person2 = JSON.parse(JSON.stringify(person));
amrender singh
  • 7,949
  • 3
  • 22
  • 28
  • Thanks it's working, But why this code does not work? persons2=[...this.persons]; – Jack Jul 28 '18 at 17:20
  • 1
    @Jack That is because the objects inside person and person2 are sharing same reference. So changes made in one will be reflected in other. – amrender singh Jul 28 '18 at 17:21
  • I did :) . I am watching this youtube tutorial: https://www.youtube.com/watch?v=1tRLveSyNz8 , on 2:07:00 He did the same like me, and it worked for him. Can you explain me please? – Jack Jul 28 '18 at 17:32
  • @Jack sure would love to :-) – amrender singh Jul 28 '18 at 17:34
  • @Jack please move a further in video the guide has mentioned that add and remove operation on the new "Array" will not be reflected in the old array. But the existing objects in the new Array and old array remains same.That is in your case if you add/remove an object in person2 two array it will not be added/removed from person array. – amrender singh Jul 28 '18 at 17:42
1

In your case both the array is referring to the same memory, which is commonly known as shallow copy.

enter image description here

You can make a deep copy of the first array and then change the second array. That will have no impact on the first array.

let persons = [{
  name: 'David',
  lname: 'Jeu'
}];

let persons2 = JSON.parse(JSON.stringify(persons));
persons2[0].age = 29;

console.log(persons)
console.log(persons2)
brk
  • 48,835
  • 10
  • 56
  • 78
1

For these kinds of operations it is usually wise using Lodash Clonedeep

mchl18
  • 2,119
  • 12
  • 20