Object in array is not updating in JavaScript

Viewed 1394

I am writing a few lines of typescript codes in an Angular application, and there are several Boolean variables at constructor, and an array of object.Part of each object in this array is formed with input vars.

selftest: boolean;
failed: boolean;

    locoStateItems = [
    {
        name: 'FAILED',
        isSelected: this.failed
    },
    {
        name: 'SELFTESTED',
        isSelected: this.selftest
    }

later on in another function

toggleMe(name: string){
   if (name === 'FAILED') {
       this.failed = !this.failed
   } else if(name === 'SELFTESTED'){
       this.selftest = !this.selftest;
   }
}

locoStateItems with are being shown in DOM are not impacted unless I explicitly write the following

locoStateItem[0].isSelected = this.failed;
locoStateItem[1].isSelected = this.selftest;

What is the explanation for this, and how I can avoid it?

1 Answers

This is because boolean is a primitive, which means that you are just assigning the value when you declare the array. This does not assign references to the boolean variables so they do not get updated in the array's objects automatically.

You will have to manually update the array objects boolean values if you intend to keep this structure.

From what I assume you would want, you should change the function to:

toggleMe(name: string){
   if (name === 'FAILED') {
       this.failed = !this.failed;
       this.locoStateItem[0].isSelected = this.failed;
   } 
   else if(name === 'SELFTESTED'){
       this.selftest = !this.selftest;
       this.locoStateItem[1].isSelected = this.selftest;
   }
}

I am not sure what is intended by this method but from what I can tell from your question this should be functional.

Related