How To Delete A Specific Item/object In Localstorage?
Turns out that my localStorage['items'] stored my JSON as a string. '['{\'itemId\':1, \'itemName\':\'item1\'}', '{\'itemId\':2, \'itemName\':\'item2\'}', '{\'\':3, \'itemName\':\'i
Solution 1:
All the answers were right but you have to :
- Parse the string in localStorage to JSON (you did that)
- Remove the item you don't want (with slice() )
- Make the JSON to string
- Re-set it in the localStorage
So :
1.
var items = JSON.parse(localStorage.getItem("items")); // updated
2.
for (var i =0; i< items.length; i++) {
var items = JSON.parse(items[i]);
if (items.itemId == 3) {
items.splice(i, 1);
}
}
3.
items = JSON.stringify(items); //Restoring object left into items again
4.
localStorage.setItem("items", items);
Parsing to JSON and storing it as string is kinda annoying, but that's the way localStorage works.
Solution 2:
Try this one.
$("#button_delete").on("click", function(e){
e.preventDefault();
var items = JSON.parse(localStorage["items"]);
for (var i = 0; i < items.length; i++) {
if(items[i].itemId == 3){
items.splice(i,1);
break;
}
}
})
Solution 3:
If you know the key
of the specific item - do it short and simple like this:
if (localStorage.getItem('key_to_remove') != null)
localStorage.removeItem('key_to_remove');
Solution 4:
localstorage can contain strings only
So first you have to parse items from localstorage (like u do now)
Remove from it the element you don't want.
Serialize it to JSON one more time and store in localstorage.
Solution 5:
Here is the approach
var items = localStorage["items"];
for (var i =0; i< items.length; i++) {
var item = JSON.parse(items[i]);
if (item.itemId == 3) {
items.slice(i);
break;
}
}
// Don't forget to store the result back in localStoragelocalStorage.setItem("items", items);
Post a Comment for "How To Delete A Specific Item/object In Localstorage?"