Localstorage & JSON: how can I remove only one array inside the key, since localstorage.removeItem requires the whole key

I have this in my local storage:

[{"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"}]

How can I delete only id:item-3when the localstorage.removeItemwhole key is required?

I use this method to update a specific value in an array: http://jsfiddle.net/Qmm9g/ , so using the same method, I want to delete a specific array.

Note that there is already a button to delete. This button I need a function that will delete the entire array ( {"id":"item-3","href":"google.com","icon":"google.com"}) usingid:item-3

+5
source share
3 answers

- , , . , , -

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

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/

, !

+6

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);
    }
+1

All Articles