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); 
1
  • splice() / slice() will to the job :) Commented Feb 6, 2015 at 9:33

6 Answers 6

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.

Sign up to request clarification or add additional context in comments.

9 Comments

Hi, I've used your method and currently it doesn't work. I've also updated the question to reflect my problem better.
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();
By the way, does localStorage['items'] works ? Try using localStorage.getItem('items').
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.
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).
|
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;
     }
  }
})

Comments

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');

Comments

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.

Comments

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);

Comments

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();
   }

1 Comment

Your answer is not much clear and understood. Could you please elaborate further? Or read this for more info: stackoverflow.com/help/how-to-answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.