如何删除localStorage中的特定项目/对象? [英] How to delete a specific item/object in localStorage?
问题描述
原来我的localStorage ["items"]将我的JSON存储为字符串.
Turns out that my localStorage["items"] stored my JSON as a string.
"["{\"itemId\":1, \"itemName\":\"item1\"}", "{\"itemId\":2, \"itemName\":\"item2\"}",
"{\"\":3, \"itemName\":\"item3\"}",]"
这是当我JSON.parse(localStorage ["items"]):时的样子:
This is what it looks like when I JSON.parse(localStorage["items"]):
["{"itemId":1, "itemName":"item1"}", "{"itemId":2, "itemName":"item2"}"
"{"itemId":3, "itemName":"item3"}"]
所以在我的循环中,我使用jQuery.parseJSON
将其变成了一个对象:
So in my loop I made it into an object by using jQuery.parseJSON
:
var object = jQuery.parseJSON(item[i]);
现在,我要删除的对象是itemId = 3
,并确保已将对象从localStorage中完全删除.
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.
到目前为止,这是我的Javascript:
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);
})
已更新
当我现在单击按钮时,它将删除该项目,但是不会删除前面的逗号.
When I click the button now, it will delete that item however it will not delete the comma before it.
当我在浏览器中检查localStorage ["items"]时,它返回以下内容:
When I check the localStorage["items"] in the browser it returns this:
"["{\"itemId\":1, \"itemName\":\"item1\"}","{\"itemId\":2, \"itemName\":\"item2\"}",null]"
我还有另一个页面,该页面将在html中显示信息,并返回错误:
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
.
那么现在有一种方法可以检查或搜索专门用于,null
的localStorage ["items"]并将其删除,以使错误不会显示出来吗?
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?
有关如何以HTML显示信息的代码:
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);
推荐答案
所有答案都是正确的,但您必须:
- 将localStorage中的字符串解析为JSON(您已经这样做了)
- 使用slice()删除不需要的项目
- 使JSON成为字符串
- 在localStorage中重新设置
所以:
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);
解析为JSON并将其存储为字符串有点烦人,但这就是localStorage的工作方式.
这篇关于如何删除localStorage中的特定项目/对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!