Javascript 如何从阵列localStorage中删除对象中的项
我设置我的Javascript 如何从阵列localStorage中删除对象中的项,javascript,local-storage,Javascript,Local Storage,我设置我的localStorage如下: category: [ {id: 1, name: "test_1"}, {id: 101, name: "test_2"} ], city: "", country: "USA", description: "", options: {transactionType: "test", desOptions: "not
localStorage
如下:
category: [
{id: 1, name: "test_1"},
{id: 101, name: "test_2"}
],
city: "",
country: "USA",
description: "",
options: {transactionType: "test", desOptions: "not found"},
phone: "",
title: ""
如果localStorage
为空,我想从中删除transactionType
或desOptions
您有解决方案或想法吗?您可以尝试以下方法:
/**
* I am assuming that your storable
* object like:
*/
const store = {
category: [
{id: 2, name: "mashin"},
{id: 102, name: "savari"}
],
city: "",
country: "Georgia",
description: "",
options: {transaction_type: "1", description: "not found"},
phone: "",
title: ""
};
localStorage = localStorage || window.localStorage;
// And you store the object into localStorage by JSON stringifying it.
localStorage.setItem('store', JSON.stringify(store));
// Get the stored item from localStorage. If nothing found then it's an empty object
let item = localStorage.getItem('store') || {};
if (!!item) {
// Parse the JSON string into JSON object
item = JSON.parse(item);
// Check if the `options` object has empty values then remove them.
item.options = Object.entries(item.options).reduce((a, [k, v]) => (!!v ? {...a, [k]: v} : a), {});
// Finally store the updated store by stringifying it.
localStorage.setItem('store', JSON.stringify(item));
}
未显示任何内容设置任何本地存储,显示的内容甚至不是有效的object@charlietfl为什么它不是一个有效的对象?@Run_脚本如果包含在
{}
@charlietfl中就有效了。询问者可能只是遗漏了代码的这一部分,只显示了对象的内容。问题似乎不在于整个对象,而在于如何从其中删除一项。此对象中有两个description
。顺便说一下,这很简单。修改对象并将其重新写入localStorage
。像符咒一样工作,tnx manitem.options=object.entries(item.options)。reduce((a,[k,v])=>(!!v?{…a,[k]:v}:a),{});//最后通过字符串化存储更新的存储。setItem('store',JSON.stringify(item))代码>