Copy array of Objects in angular 2

自古美人都是妖i 提交于 2020-03-22 07:07:28

问题


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]);
  }

}

回答1:


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));



回答2:


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

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)



回答3:


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



来源:https://stackoverflow.com/questions/51573579/copy-array-of-objects-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!