6

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); 
ahfreak
  • 119
  • 2
  • 4
  • 11

6 Answers6

9

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.

Heemanshu Bhalla
  • 3,603
  • 1
  • 27
  • 53
enguerranws
  • 8,087
  • 8
  • 49
  • 97
  • Hi, I've used your method and currently it doesn't work. I've also updated the question to reflect my problem better. – ahfreak Feb 06 '15 at 10:13
  • What does the console tells you ? Any errors ? Be sure to put console.log(); to debug values easier. Also, instead of String() try items = items.toString(); – enguerranws Feb 06 '15 at 16:17
  • By the way, does localStorage['items'] works ? Try using localStorage.getItem('items'). – enguerranws Feb 06 '15 at 16:20
  • I looked into a project where I worked a lot with localStorage, I was using JSON.stringify() to stringify my JSON array. I updated my answer. – enguerranws Feb 06 '15 at 16:23
  • And note you made a confusion between items and item (I choose to only use items as it surely will be an array of elements). – enguerranws Feb 06 '15 at 16:31
  • Updated my question again and edit the errors I made. `slice` doesn't work, not sure why but I used `delete` and it's able to remove it from the `localStorage['items'].` – ahfreak Feb 07 '15 at 07:18
  • However there's one last problem which I stated in my updated question. Would really appreciate it if you can figure it out. – ahfreak Feb 07 '15 at 07:19
  • I guess you shouldn't use delete (I think it remove the object, so it turns to null, but the entry in the items array is still there), but slice() or splice(). items.splice(i,1) doesn't work too ? And just to be sure, when you loop, you should check if items[i] exists (if(items[i]), just to be sure it won't break in some cases. – enguerranws Feb 07 '15 at 10:13
  • Oh wait. slice() doesn't work but splice() does. Thanks! It should be solved by now. – ahfreak Feb 07 '15 at 10:23
5

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;
     }
  }
})
skmahawar
  • 313
  • 1
  • 13
4

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');
Jonathan Applebaum
  • 5,738
  • 4
  • 33
  • 52
1

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.

marcinn
  • 1,786
  • 11
  • 13
1

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 localStorage
localStorage.setItem("items", items);
kasper Taeymans
  • 6,950
  • 5
  • 32
  • 51
Praveen
  • 55,303
  • 33
  • 133
  • 164
0
 eliminar(est: string) {
     //estudiantes ES LA KEY
    var items = JSON.parse(localStorage.getItem('estudiantes'));
    for (var i = 0; i < items.length; i++) {

      var item = items[i];
       if(item.id == est){
         items.splice(i,1);
       }     
    }
    items = JSON.stringify(items);
    localStorage.setItem('estudiantes', items);
    this.getAll();
   }
  • 2
    Your answer is not much clear and understood. Could you please elaborate further? Or read this for more info: https://stackoverflow.com/help/how-to-answer – shhdharmen Nov 12 '19 at 17:37