I want to delete an object from an array stored in local storage. With this.storage.remove(key); I can only remove the whole array.A solution i found says that i have to remove the whole array, and then save the new one without the element i want to delete.Is this the only way? Or can i just save a new array with the same key and the old one will me overwritten?
lets say this what i have in localstorage.
Key of the array: "My-Key"
Items of the array: "[{"title":"item1","content":"content 11"}, {"title":"item2","content":"content 2"}]"
Item to remove: {"title":"item2","content":"content 2"}
This will solve your problem:
function removeItem(item_title) {
localStorage.setItem(
"My-Key",
JSON.stringify(
JSON.parse(localStorage.getItem("My-key")).filter(item => {
return item.title !== item_title;
})
)
);
}
removeItem("item2");
Also, since you are working with localStorage
, I would like to recommend you this tiny JS library, which will make it much easier to work with localStorage
as well as sessionStorage
and some other things alongside:
https://github.com/tranclix/XJS
By using XJS, the above code will be like this:
function removeItem(item_title) {
x.jls(
"My-Key",
x.jlg("My-key").filter(item => {
return item.title !== item_title;
})
);
}
removeItem("item2");