I have this function to push data into the array and save it in localstorage. My problem is that my function pushes to the array/saves to localstorage even though the same profileID exists. I want something that checks if the same profileId already exists remove the object and from localstorage/array then push to local storage/array. In short i do not want duplicates of the same profileID saved in localstorage or the array. I also want to keep the most new object instead of old and new saved in the array for the same profilID
PUSHData(){
var myobj = {
Button: this.isReadMore,
Class: this.sampleElem.className,
ProfiliD: this.id,
};
const saved = JSON.parse(localStorage.getItem('CollapseState'));
if(saved != null){
this.array.push(myobj);
localStorage.setItem('CollapseState',JSON.stringify(this.array));
}else{
this.array.push(myobj);
localStorage.setItem('CollapseState',JSON.stringify(this.array));
}
this is what localStorage looks like now
0: {Button: true, Class: "ShowHide", ProfiliD: "115279"}
1: [{Button: true, Class: "ShowHide", ProfiliD: "115279"},…]
0: {Button: true, Class: "ShowHide", ProfiliD: "115279"}
1: [{Button: true, Class: "ShowHide", ProfiliD: "115192"}]
I would really appreciatie any help
you should update existing item in array instead of push new one when same ProfiliD exists in localStorage:
PUSHData(){
var myobj = {
Button: this.isReadMore,
Class: this.sampleElem.className,
ProfiliD: this.id,
};
const saved = JSON.parse(localStorage.getItem('CollapseState'));
if(saved != null){
this.array[this.array.findIndex(x=>x.ProfiliD == myobj.ProfiliD)] = myobj;
localStorage.setItem('CollapseState',JSON.stringify(this.array));
}else{
this.array.push(myobj);
localStorage.setItem('CollapseState',JSON.stringify(this.array));
}
}
As CollapseState is containing an array of objects in a localStorage. You can follow below steps to achieve this requirement :
Check if CollapseState array exist in localStorage or not (which you already doing)
const saved = JSON.parse(localStorage.getItem('CollapseState'));
Now as saved will be an array, You can iterate over it to check if ProfiliD exist or not. If exist, splice/remove the object from the array.
saved.forEach((o, index) => {
if (o.ProfiliD === myobj.ProfiliD) {
saved.splice(index, 1);
}
});
Now push the newObj into the saved array.
saved.push(newObj);
Final step, set this updated saved array into the localStorage.
localStorage.setItem('CollapseState',JSON.stringify(saved));