Skip to content Skip to sidebar Skip to footer

Localstorage & Json: How Can I Delete Only 1 Array Inside A Key Since Localstorage.removeitem Requires The Entire Key

I have this in my localStorage: [{'id':'item-1','href':'google.com','icon':'google.com'}, {'id':'item-2','href':'youtube.com','icon':'youtube.com'}, {'id':'item-3','href':'google.

Solution 1:

Something like this would work, I'm not sure if it's the best way to do it though. There maybe a better local storage specific way -

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

Solution 2:

You can use jQuery's $.each() function along with JavaScript's splice method to remove the entire object like this:

$.each(json, function(index, obj){
    if (obj.id == 'item-3') {
        json.splice(index,1);
        console.log(json);
        localStorage["results"] = JSON.stringify(json);
        returnfalse;
    }
});

Updated Fiddle: http://jsfiddle.net/Qmm9g/3/

I hope this helps!

Solution 3:

This is my code to delete object from 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"}
    ]
 }


    functionfilterData() {
        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);
    }

Post a Comment for "Localstorage & Json: How Can I Delete Only 1 Array Inside A Key Since Localstorage.removeitem Requires The Entire Key"