[英]How to delete only one element in an array from the local storage?
var details = [{
"Name": "Bhavani",
"Phone No": ["123456", "123456"],
"Email Id": ["mamata@gmail.com", "mamata@yahoo.com"],
"Birthday": "21/16/22/33"
}, {
"Name": "Mamata",
"Phone No": ["123456", "123456"],
"Email Id": ["mamata@gmail.com", "mamata@yahoo.com"],
"Birthday": "21/16/22/33"
}];
function add() {
localStorage.setItem('contacts', JSON.stringify(details));
str = localStorage.getItem("contacts");
}
function removeItems(){
var s = localStorage.removeItem("contacts");
alert(s);
}
如何刪除數組中的一個元素而不刪除整個本地存儲?
問題下我的評論的代碼示例-從Mamata刪除電子郵件ID:
var details = JSON.parse(localStorage.getItem('contacts'));
details.filter(function(e) {
return e.Name === "Mamata"
}).forEach(function(element) {
delete element["Email Id"];
});
localStorage.setItem('contacts', JSON.stringify(details));
編輯 :如果要刪除整個記錄而不是其中的字段,則應這樣做:
var details = JSON.parse(localStorage.getItem('contacts'));
details = details.filter(function(e) {
return e.Name !== "Mamata"
});
localStorage.setItem('contacts', JSON.stringify(details));
localStorage.setItem("contacts",localStorage.getItem("contacts").split(',').splice(...));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.