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

3
  • 1
    You are getting a reference to an element in the array. So you are basically editing the item in the array. Commented Jun 20, 2018 at 6:06
  • Deep Cleaning for array comes to rescue here !! Commented Jun 20, 2018 at 6:20
  • pass by reference vs pass by value Commented Jun 20, 2018 at 6:31

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

2 Comments

JSON.parse(JSON.stringify()); is not perfact for all case and not recommended by community
Thanks. Suggesting "community recommended" approach for deep cloning would help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.