简体   繁体   中英

Remove Local Storage JSON Object & Rebuild Array

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM