Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a key within an object in local storage with Javascript and/or Jquery?

In local storage I have an object named favourites and it contains this..

"{
    "id3333":{
        "URL":"somewhere.comm/page1/",
        "TITLE":"Page 1 Title",
    },
    "id4444":{
        "URL":"somewhere.comm/page2/",
        "TITLE":"Page 2 Title",
    }
}"

How can I delete an object based on its ID (id3333 & id4444 for examples)

I have tried the following along with some other voodoo..

localStorage.removeItem('id3333'); // no errors, no removal
localStorage.removeItem('favourites':'id3333'); // SyntaxError: missing ) after argument list
localStorage.removeItem('favourites[id3333]'); // no errors, no removal
localStorage.removeItem('id3333', JSON.stringify('id3333')); // no errors, no removal

Also, I will need to get the key name to delete based on a variable, so like this..

var postID = 'id3333';
localStorage.removeItem(postID);

or

var objectName = 'favourites';
var postID = 'id3333';
localStorage.removeItem(objectName[postID]);

Is it possible to remove a nested item directly or do I need to retrieve the full object and then delete the item and then set the object back to local storage again?

The closest I can get to deleting anything directly so far is..

localStorage.removeItem('favourites');

But that of course removes the entire object.

like image 353
Hastig Zusammenstellen Avatar asked Jan 05 '23 16:01

Hastig Zusammenstellen


1 Answers

You have a a single key and you are acting like there are multiple keys

var obj = {
    "id3333":{
        "URL":"somewhere.comm/page1/",
        "TITLE":"Page 1 Title",
    },
    "id4444":{
        "URL":"somewhere.comm/page2/",
        "TITLE":"Page 2 Title",
    }
};

window.localStorage.favs = JSON.stringify(obj);  //store object to local storage
console.log("before : ", window.localStorage.favs);  //display it
var favs = JSON.parse(window.localStorage.favs || {});  //read and convert to object
var delKey = "id3333";  //key to remove
if (favs[delKey]) {  //check if key exists
    delete favs[delKey];  //remove the key from object
}
window.localStorage.favs = JSON.stringify(favs);  //save it back
console.log("after : ", window.localStorage.favs);  //display object with item removed
like image 81
epascarello Avatar answered Jan 17 '23 16:01

epascarello