简体   繁体   English

以角度2复制对象数组

[英]Copy array of Objects in angular 2

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. 我有两个名为'people'和'persons2'的数组,'persons2'数组将是'people'数组的副本,但问题是当我复制它时,我想要更改第二个数组,第一个数组是也在改变。 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]);
  }

}

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

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) 

对于这些类型的操作,通常使用Lodash Clonedeep是明智的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM