Home > database >  Updating object property inside an array of objects
Updating object property inside an array of objects

Time:06-27

I'm trying to update a property in an object inside an array using an EventEmitter in a child component.

interface productItem {
  keepOpen: boolean;
}

products$:productItem[] = Array(7).fill(
    {
      keepOpen:false
    }
  )

I'm using this function when the user clicks on the button :

shouldKeepAddToBagOpen(dataFromChild: boolean, index: number): void {
    // handle callback
    this.keepAddToBagOpen = dataFromChild;
    this.products$[index].keepOpen = dataFromChild;
 
  }

However it is affecting all the items in the array, not only the one with the given index: enter image description here

What am I doing wrong?

CodePudding user response:

When Array.fill gets passed an object, it will copy the reference and fill the array with references to that object.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill#using_fill

You could instead use something like:

products = Array.from({length:7},()=> ({'keepOpen':false}))

  • Related