Localstorage&JSON:我如何只删除一个键中的一个数组,因为localstorage.removeItem需要整个键

jQu*_*ast 5 arrays jquery html5 json local-storage

我在localStorage中有这个:

[{"id":"item-1","href":"google.com","icon":"google.com"},
{"id":"item-2","href":"youtube.com","icon":"youtube.com"},
{"id":"item-3","href":"google.com","icon":"google.com"},
{"id":"item-4","href":"google.com","icon":"google.com"},
{"id":"item-5","href":"youtube.com","icon":"youtube.com"},
{"id":"item-6","href":"asos.com","icon":"asos.com"},
{"id":"item-7","href":"google.com","icon":"google.com"},
{"id":"item-8","href":"mcdonalds.com","icon":"mcdonalds.com"}]
Run Code Online (Sandbox Code Playgroud)

我怎么能只删除id:item-3时,localstorage.removeItem需要整个键?

我使用此方法更新数组中的特定值:http://jsfiddle.net/Qmm9g/所以使用相同的方法我想删除特定的数组.

请注意,已有一个要删除的按钮.那个按钮我想要一个将删除整个数组({"id":"item-3","href":"google.com","icon":"google.com"})的函数ID:item-3

ipr*_*101 8

这样的东西会起作用,但我不确定它是不是最好的方法.可能有更好的本地存储特定方式 -

var json = JSON.parse(localStorage["results"]);
for (i=0;i<json.length;i++)
            if (json[i].id == 'item-3') json.splice(i,1);
localStorage["results"] = JSON.stringify(json);
Run Code Online (Sandbox Code Playgroud)


dSq*_*red 6

您可以使用jQuery的$ .each()函数以及JavaScript的splice方法来删除整个对象,如下所示:

$.each(json, function(index, obj){
    if (obj.id == 'item-3') {
        json.splice(index,1);
        console.log(json);
        localStorage["results"] = JSON.stringify(json);
        return false;
    }
});
Run Code Online (Sandbox Code Playgroud)

更新小提琴:http://jsfiddle.net/Qmm9g/3/

我希望这有帮助!