Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/413.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从阵列localStorage中删除对象中的项_Javascript_Local Storage - Fatal编程技术网

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 man
item.options=object.entries(item.options)。reduce((a,[k,v])=>(!!v?{…a,[k]:v}:a),{});//最后通过字符串化存储更新的存储。setItem('store',JSON.stringify(item))