admin管理员组

文章数量:1292149

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

"{
    "id3333":{
        "URL":"somewherem/page1/",
        "TITLE":"Page 1 Title",
    },
    "id4444":{
        "URL":"somewherem/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.

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

"{
    "id3333":{
        "URL":"somewhere.m/page1/",
        "TITLE":"Page 1 Title",
    },
    "id4444":{
        "URL":"somewhere.m/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.

Share edited Jul 22, 2016 at 4:50 Hastig Zusammenstellen asked Jul 22, 2016 at 3:17 Hastig ZusammenstellenHastig Zusammenstellen 4,4403 gold badges34 silver badges45 bronze badges 1
  • 1 You can store only strings in localStorage, not objects. So your only choice is to load the entire string in memory, manipulate it, then save it back. The JSON methods work perfectly for this, as @epascarello demonstrates. – Rick Hitchcock Commented Jul 22, 2016 at 3:39
Add a ment  | 

4 Answers 4

Reset to default 6

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

var obj = {
    "id3333":{
        "URL":"somewhere.m/page1/",
        "TITLE":"Page 1 Title",
    },
    "id4444":{
        "URL":"somewhere.m/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

With localStorage.removeItem you can only remove top level keys, i.e. keys directly on localStorage.

Because id3333 is on localStorage.favourites you cannot remove it using localStorage.removeItem.

Instead try delete localStorage.favourties['id3333']

Simple, actually: you just delete it. :)

x = {
    "id3333":{
        "URL":"somewhere.m/page1/",
        "TITLE":"Page 1 Title",
    },
    "id4444":{
        "URL":"somewhere.m/page2/",
        "TITLE":"Page 2 Title",
    }
};
console.log(x);
delete x.id3333;
console.log(x);

delete does what you're looking for. You could also do something like delete x.id3333.TITLE if you were so inclined. Note also that delete returns true if successful and false if not.

Suppose you set a nested object in localStorage like that

const dataObj = {
    uid: {
        name: 'robin',
        age: 24,
    }

} 

window.localStorage.setItem('users', JSON.stringify(dataObj));

Now you want to delete the age property. You can't remove it with removeItem native function since it allows to delete from top level.

So you need to get the data first and delete the property you want and set the data again to localStorage with updated value like that

const existingLocalStorage = JSON.parse(window.localStorage.getItem('users') || {});
if(existingLocalStorage['uid']['age']) { // if throws any error, use lodash get fucntion for getting value
    delete existingLocalStorage['uid']['age'];
}
window.localStorage.setItem('users', JSON.stringify(existingLocalStorage));

本文标签: How to delete a key within an object in local storage with Javascript andor JqueryStack Overflow