[英]How to delete a key within an object in local storage with Javascript and/or Jquery?
在本地存儲中,我有一個名為favourites
的對象,它包含這個..
"{
"id3333":{
"URL":"somewhere.comm/page1/",
"TITLE":"Page 1 Title",
},
"id4444":{
"URL":"somewhere.comm/page2/",
"TITLE":"Page 2 Title",
}
}"
如何根據對象的 ID 刪除對象(例如 id3333 和 id4444)
我已經嘗試了以下以及其他一些伏都教..
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
另外,我需要根據變量獲取要刪除的鍵名,所以像這樣..
var postID = 'id3333';
localStorage.removeItem(postID);
或
var objectName = 'favourites';
var postID = 'id3333';
localStorage.removeItem(objectName[postID]);
是否可以直接刪除嵌套項目,還是需要檢索完整對象,然后刪除該項目,然后再次將對象設置回本地存儲?
到目前為止,我最接近直接刪除任何內容的是..
localStorage.removeItem('favourites');
但這當然會刪除整個對象。
你有一個單一的鑰匙,你的行為就像有多個鑰匙
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
使用localStorage.removeItem
您只能刪除頂級鍵,即直接在localStorage
上的鍵。
因為id3333
在localStorage.favourites
,所以不能使用localStorage.removeItem
刪除它。
而是嘗試delete localStorage.favourties['id3333']
實際上很簡單:您只需delete
它即可。 :)
x = {
"id3333":{
"URL":"somewhere.comm/page1/",
"TITLE":"Page 1 Title",
},
"id4444":{
"URL":"somewhere.comm/page2/",
"TITLE":"Page 2 Title",
}
};
console.log(x);
delete x.id3333;
console.log(x);
delete
做你正在尋找的。 如果您願意,也可以執行諸如delete x.id3333.TITLE
。 另請注意,如果成功,則delete
返回true
否則返回false
。
假設你在 localStorage 中設置了一個嵌套對象
const dataObj = {
uid: {
name: 'robin',
age: 24,
}
}
window.localStorage.setItem('users', JSON.stringify(dataObj));
現在您要刪除age
屬性。 您不能使用removeItem
本機函數刪除它,因為它允許從頂級刪除。
因此,您需要先獲取數據並刪除所需的屬性,然后將數據再次設置為具有更新值的 localStorage
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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.