0

I am looking for a way to delete one object in an array, without having to delete all the local storage, like by using local.storage.clear

I tried using Local.storage.removeItem but it didn't work. I also used JSON.stringify to set the item, is there any alternative? Thank you!

<!DOCTYPE html> <html> <body> <p id="demo"></p> <input id="click"type="checkbox" onclick="savelocalstorage()"> </button> <script> var n=0; function savelocalstorage() { var myarray = [ { format: "jpg", name: "Alice" }, { format: "jpg", name: "Jack" }, ]; if (n % 2 == 1) { document.getElementById("click").checked = false; localStorage.removeItem(myarray[0]); } else { document.getElementById("click").checked = true; localStorage["myarray"] = JSON.stringify(myarray[0]); } n++; } </script> </body> </html> 
2
  • 1
    In the localStorage you are saving in "myarray", why are you trying to delete a different thing? Don't you have to dolocalStorage.removeItem("myarray"); Commented Nov 6, 2018 at 15:25
  • @BrankVictoria should be right. You are passing in an object to look for to remove, but you should be looking for the item name ex: localStorage.removeItem('itemName');. Commented Nov 6, 2018 at 15:28

3 Answers 3

2

The key for localstorage must be a string, you are passing an object which cannot be a key

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

5 Comments

Actually he is passing "myarray" as key
Not here he isn't: localStorage.removeItem(myarray[0]);
Yes, but if you see what he is storing in the localStorage with key"myarray" is the whole array of objects using JSON.stringify, he is not storing the object itself
i see that @BrankVictoria
@vwvwvw Yes you can, but you need to store it using a key, I supossed you can use the stringify of the object as the key and value... Then you will remove it using the stringify again...
1

You're doing this:

localStorage.removeItem(myarray[0]);

But myarray[0] is an object, whereas the key you're storing the object in is the string "myarray". Use the string in both cases.

Comments

0

You need to get the item from the local storage m the remove first element and store it back

var n = 0; function savelocalstorage() { var myarray = [{ format: "jpg", name: "Alice" }, { format: "jpg", name: "Jack" } ]; if (n % 2 == 1) { document.getElementById("click").checked = false; // get the storage & remove the first element let itm = JSON.parse(localStorage.getItem('myarray')).shift(); localStorage.setItem('myarray', JSON.stringify(itm)); } else { document.getElementById("click").checked = true; localStorage.setItem("myarray",JSON.stringify(myarray[0])); } n++; }
<p id="demo"></p> <input id="click" type="checkbox" onclick="savelocalstorage()">

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.