Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.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 the id:item-3 when localstorage.removeItem requires entire key?

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 specific array.

Note that there is already a button to delete. That button I want a function which will delete the entire array ({"id":"item-3","href":"google.com","icon":"google.com"}) with ID:item-3

like image 466
jQuerybeast Avatar asked Nov 14 '11 19:11

jQuerybeast


3 Answers

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);
like image 91
ipr101 Avatar answered Nov 17 '22 14:11

ipr101


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);
        return false;
    }
});

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

I hope this helps!

like image 28
dSquared Avatar answered Nov 17 '22 13:11

dSquared


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


    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);
    }
like image 1
Shagun1390 Avatar answered Nov 17 '22 13:11

Shagun1390