繁体   English   中英

如何从数组 localStorage 中删除 object 中的项目

[英]How can remove item in object from array localStorage

我将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中删除transactionTypedesOptions

你有解决方案或想法吗?

你可以试试这个:

/**
* 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));

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM