如何从本地存储中删除对象
How to remove object from local storage
这是我的代码,我想从本地存储中删除 https://prnt.sc/j9Un7C5nxDCZ 自定义包 1 对象我试过 removeitem() 但它没有删除我的对象
var all_pack = JSON.parse(localStorage.getItem("CartItems"));
var object_length = Object.keys(all_pack).length;
var selected_option = "custom meal pack-1";
for (var i = 0; i < object_length; i++) {
var p = Object.keys(all_pack)[i];
if (selected_option === p) {
Object.keys(all_pack)[i].removeItem();
}
}
存储字符串。您必须读取字符串、解析它、修改它、序列化它并写回它。
您的代码片段让我假设,您不想从存储中删除项目,而是要从存储在本地存储中的对象中删除 属性。
const all_pack = JSON.parse(localStorage.getItem("CartItems"));
const selected_option = "custom meal pack-1";
for (key in all_pack) {
if (selected_option === key) {
delete all_pack[key];
}
}
// update local storage
// localStorage.setItem("CartItems", JSON.stringify(all_pack));
示例:
const all_pack = JSON.parse('{ "custom meal pack-1": true, "custom meal pack-2": true}');
const selected_option = "custom meal pack-1";
for (key in all_pack) {
if (selected_option === key) {
delete all_pack[key];
}
}
console.log(all_pack);
这是我的代码,我想从本地存储中删除 https://prnt.sc/j9Un7C5nxDCZ 自定义包 1 对象我试过 removeitem() 但它没有删除我的对象
var all_pack = JSON.parse(localStorage.getItem("CartItems"));
var object_length = Object.keys(all_pack).length;
var selected_option = "custom meal pack-1";
for (var i = 0; i < object_length; i++) {
var p = Object.keys(all_pack)[i];
if (selected_option === p) {
Object.keys(all_pack)[i].removeItem();
}
}
存储字符串。您必须读取字符串、解析它、修改它、序列化它并写回它。
您的代码片段让我假设,您不想从存储中删除项目,而是要从存储在本地存储中的对象中删除 属性。
const all_pack = JSON.parse(localStorage.getItem("CartItems"));
const selected_option = "custom meal pack-1";
for (key in all_pack) {
if (selected_option === key) {
delete all_pack[key];
}
}
// update local storage
// localStorage.setItem("CartItems", JSON.stringify(all_pack));
示例:
const all_pack = JSON.parse('{ "custom meal pack-1": true, "custom meal pack-2": true}');
const selected_option = "custom meal pack-1";
for (key in all_pack) {
if (selected_option === key) {
delete all_pack[key];
}
}
console.log(all_pack);