Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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\":\"item3\"}",]"

This is what it looks like when I JSON.parse(localStorage["items"]):

["{"itemId":1, "itemName":"item1"}", "{"itemId":2, "itemName":"item2"}"
"{"itemId":3, "itemName":"item3"}"]

So in my loop I made it into an object by using jQuery.parseJSON:

var object = jQuery.parseJSON(item[i]);

Right now, what I want to do is delete the object where itemId = 3 and make sure that the object is totally removed from the localStorage.

Here's my Javascript so far:

$("#button_delete").on("click", function(e){
  e.preventDefault();

  var items = JSON.parse(localStorage.getItem('items'));
    for (var i = 0; i < items.length; i++) {

      var object = JSON.parse(items[i]);
       if(object.request_id == 3){
         console.log(items) 
         delete items[i] // slice doesn't work not sure why
         console.log(items)
       }     
    }

    item = JSON.stringify(items);
    console.log(item);
    localStorage.setItem('items', item);
})

UPDATED

When I click the button now, it will delete that item however it will not delete the comma before it.

When I check the localStorage["items"] in the browser it returns this:

"["{\"itemId\":1, \"itemName\":\"item1\"}","{\"itemId\":2, \"itemName\":\"item2\"}",null]"

I have another page that will display the info in the html and it returns the error:

Uncaught TypeError: Cannot read property 'itemId' of null.

So right now is there a way to check or search in localStorage["items"] specifically for ,null and remove it so that the error won't show?

Code on how I'm displaying the info in HTML:

    var items = JSON.parse(localStorage.getItem('items'));
    var itemsHTML = "";

    for(var i = 0; i < items.length; i++){

      var object = jQuery.parseJSON(items[i]);

      var displayItemId = object.itemId;
      var displayItemName = object.itemName;

      itemsHTML += "<li id="+displayItemId+">"+displayItemName+"</li>";
    }

    $("#viewItemList").html(itemsHTML); 
like image 522
ahfreak Avatar asked Feb 06 '15 09:02

ahfreak


Video Answer


4 Answers

All the answers were right but you have to :

  1. Parse the string in localStorage to JSON (you did that)
  2. Remove the item you don't want (with slice() )
  3. Make the JSON to string
  4. 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.

like image 90
enguerranws Avatar answered Oct 26 '22 13:10

enguerranws


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;
     }
  }
})
like image 45
skmahawar Avatar answered Oct 26 '22 15:10

skmahawar


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');
like image 21
Jonathan Applebaum Avatar answered Oct 26 '22 13:10

Jonathan Applebaum


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.

like image 21
marcinn Avatar answered Oct 26 '22 14:10

marcinn