1

Why my array element is getting updated when another variable which gets a copy of one of the item in the array is updated?

StackBlitz: https://stackblitz.com/edit/angular-3tgp7h

(check AppComponent)

Code:

export class AppComponent implements OnInit  {
  materials: Material[] = [];
  material: Material;

  ngOnInit(){
    
    this.materials = [
      {
        name: 'One',
        price:10,
      },
      {
        name: 'Two',
        price:10,
      },
      {
        name: 'Three',
        price:10,
      },
    ];

    this.material = this.materials.find(mat => mat.name === 'One');

    console.log('material ones price in the array: '+this.materials.find(mat => mat.name === 'One').price )

    //Update (single) material object

    this.material.price = 20;

   // below is displaying 20. but i didn't update array
   // why is this happening?
    console.log('material ones price in the array after update: '+this.materials.find(mat => mat.name === 'One').price )
  }
}

export interface Material {
  name: string;
  price: number;
}
Anshuman Jaiswal
  • 5,352
  • 1
  • 29
  • 46

1 Answers1

3

It will give you reference of that object

this.material = this.materials.find(mat => mat.name === 'One');

And that's why it's updating the value in source array.

You can create a deep clone as:

let foundObj = this.materials.find(mat => mat.name === 'One');
if(foundObj) {
    foundObj = JSON.parse(JSON.stringify(foundObj));
}
this.material = foundObj;
Anshuman Jaiswal
  • 5,352
  • 1
  • 29
  • 46