Remove Local Storage JSON Object & Rebuild Array

时间:2016-04-25 08:50:36

标签: javascript json object local-storage

I'm struggling with the task of removing an item from the LocalStorage...here is my LocalStorage data JSON.

{
"1461569942024" : 
{"t_id":1461569942024,"t_build_val":"PreBuild1","t_project_val":"18"},
"1461570048166" : 
{"t_id":1461570048166,"t_build_val":"PreBuild2","t_project_val":"17"}
}

here is what I was trying to do:

function removeItem(array, value) {
    var idx = array.indexOf(value);
    if (idx !== -1) {
        array.splice(idx, 1);
    }
    return array;
}

var newData = removeItem(localStorage['data'], '1461569942024');

I would like to remove na object based on object key eg:1461570048166 and re-save whole array again to the LocalStorage.

Thanks

1 个答案:

答案 0 :(得分:0)

Try this code

var json = {
    "1461569942024": {
        "t_id": 1461569942024,
        "t_build_val": "PreBuild1",
        "t_project_val": "18"
    },
    "1461570048166": {
        "t_id": 1461570048166,
        "t_build_val": "PreBuild2",
        "t_project_val": "17"
    }
};

function deleteItem(input, key) {

    delete input[key];

    return input

}

localStorage.setItem("localStore", JSON.stringify(json));

localStorage.setItem("localStore", JSON.stringify(deleteItem(JSON.parse(localStorage.getItem("localStore")), '1461570048166')));

JSON.parse(localStorage.getItem("localStore"));