复制角度2中的对象数组 [英] Copy array of Objects in angular 2

查看:79
本文介绍了复制角度2中的对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组,分别称为"persons"和"persons2", "persons2"数组将是"persons"数组的副本, 但是问题是当我复制它,并且想更改第二个数组时,第一个数组也在更改.这是我的代码:

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

}

推荐答案

但是问题是当我复制它时,我想更改第二个 数组,第一个数组也在改变

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

let person2 = JSON.parse(JSON.stringify(person));

这篇关于复制角度2中的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆