Home > OS >  Changing attribute of an object inside LocalStorage?
Changing attribute of an object inside LocalStorage?

Time:09-17

in my template I have an onclick-event, which is calling a method, that is supposed to change one attribute "status: boolean" of an object "eintrag" to true.

<input type="checkbox" (change)="eintrag.status= !eintrag.status" onclick="changeStatus(eintrag)"/>

This object is inside an array eintraege: Eintrag[] = []; and is saved inside a LocalStorage this.eintragService.saveData('token', JSON.stringify(this.eintraege))

Is there a way to implement changeStatus in a way, that I can change the attribute status in there and put it in the same index as it was, without deleting it? Or is it not possible with arrays?

Eintrag:

export interface Eintrag {
  beschreibung: string;
  status: boolean;
  faelligkeitsdatum: string;
}

For now, changeStatus is empty, all I do is finding the index of the "eintrag" inside the array:

this.eintrag = eintrag;
    const beschreibung = this.eintrag.beschreibung;
    const index = this.eintraege.findIndex(eintrag => eintrag.beschreibung === beschreibung);

Then I can delete the eintrag at the index, but I want it to be replaced there:

if (index > -1) {
  this.eintraege.splice(index, 1);
}

CodePudding user response:

interface Eintrag {
  beschreibung: string;
  status: boolean;
  faelligkeitsdatum: string;
}

const eintraege: Eintrag[] = [
  { beschreibung: 'foo', status: false, faelligkeitsdatum: 'foo' },
  { beschreibung: 'bar', status: false, faelligkeitsdatum: 'bar' },
  { beschreibung: 'zoo', status: false, faelligkeitsdatum: 'zoo' },
];

/* the following line is meant to be executed just once, for the local
storage initialization, then it should be commented and only the 
updateEintraegeLocalStorage method to be executed for tests */

localStorage.setItem('token', JSON.stringify(eintraege));

const updateEintraegeLocalStorage = (elementIndexToUpdateStatus) => {
  let eintraege = JSON.parse(localStorage.getItem('token'));

  const statusOfEintragToUpdate = eintraege[elementIndexToUpdateStatus]['status'];
  eintraege[elementIndexToUpdateStatus]['status'] = !statusOfEintragToUpdate;

  localStorage.setItem('token', JSON.stringify(eintraege));
};

/* index is a mock that you find in your code using
this.eintraege.findIndex(eintrag => eintrag.beschreibung === 
 beschreibung); 
*/
const index = 0;

updateEintraegeLocalStorage(index);
  • Related