I'm facing an issue with the function I have for pushing data into an array and saving it in local storage. The problem is that the function adds the data to the array/local storage even if the same profileID already exists. I want a solution that checks if the same profileID exists, removes the old object from local storage/array, and then adds the new data. Essentially, I want to avoid duplicates of the same profileID being saved in local storage or the array. Additionally, I want to ensure that only the most recent object is saved for the same profileID, overriding any older data.
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 the current content of localStorage:
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"}]
Any assistance would be greatly appreciated.