Ravi Kumar BG
Ravi Kumar BG

Reputation: 23

Angular/Typescript: arrays in typescript changing when an independent element got changed

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

Upvotes: 1

Views: 70

Answers (1)

Anshuman Jaiswal
Anshuman Jaiswal

Reputation: 5462

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;

Upvotes: 3

Related Questions