admin管理员组文章数量:1278912
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]);
}
}
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]);
}
}
Share
Improve this question
asked Jul 28, 2018 at 17:14
JackJack
895 silver badges12 bronze badges
1
- 1 Duplicate with every other question here... – Akxe Commented Jul 28, 2018 at 17:18
3 Answers
Reset to default 8But 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 monly 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)
For these kinds of operations it is usually wise using Lodash Clonedeep
本文标签: javascriptCopy array of Objects in angular 2Stack Overflow
版权声明:本文标题:javascript - Copy array of Objects in angular 2 - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741240149a2363815.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论