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

我在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"}] 

localstorage.removeItem需要整个密钥时,如何只删除id:item-3

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

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

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

 var json = JSON.parse(localStorage["results"]); for (i=0;i 

您可以使用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; } }); 

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

我希望这有帮助!

这是我从localStorage中删除对象的代码。

  { "admin": { "pass": "1234", "task": [ {"id": "1", "taskName": "assignedTask", "taskDesc": "jhdjshdh"}, {"id": "2", "taskName": "assignedTask", "taskDesc": "jhdjshdh"}, {"id": "3", "taskName": "assignedTask", "taskDesc": "jhdjshdh"}, {"id": "4", "taskName": "assignedTask", "taskDesc": "jhdjshdh"} ] } function filterData() { var data = JSON.parse(localStorage.task); //console.log(data); var newData = data.filter(function(val){ return (val.YourPropertyName !== key.value && val.YourPropertyName !== val.value ); }); localStorage.task = JSON.stringify(newData); }