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]);
}
}
That is because the objects inside both the arrays are sharing same reference. To perform a deep copy try the following :
Or