Why isn't my array saving all data i choose?


#1

When i open up a modal, it saves what i choose but then when i want to save another data it rewrites the data on the last ones it save.

HTML

  <ion-list radio-group>
        <ion-item *ngFor="let d of data">
          <ion-label>{{d}}</ion-label>
          <ion-radio value="{{d}}" [checked] 
          (click)="seleccionarPrestador(d)">
          </ion-radio>
        </ion-item>
      </ion-list>

Function

seleccionarPrestador(d){
      console.log(d); 
      for(var i=0; i<this.data.length; i++){
        if(d == this.data[i]){
         this.idc =this.idcert[i];
         this.idcertificado.push(this.idc);  
              
          }
        }
        console.log(this.idcertificado);
     }

i’ve tried putting this.idcertificado.push(this.idc); and console.log(this.idcertificado); on another function but it’s the same thing


#2

You haven’t really told us what all the data looks like, but my suspicion is you are facing this problem because of this.idc. Assuming this.idc will contain an object and not a primitive type, when you do a push it pushes a reference to the object. So if you change the value of this.idc later, it will effectively overwrite the previous value stored in your idcertificado array (because your previous idcertificado element you pushed is simply pointing to wherever this.idc will point to, which has now changed.)

Summary: try changing this.idc =this.idcert[i]; to let idc =this.idcert[i];
and this.idcertificado.push(this.idc); to this.idcertificado.push(idc);