简体   繁体   中英

How can remove item in object from array localStorage

I set my localStorage like bottom:

category: [
  {id: 1, name: "test_1"},
  {id: 101, name: "test_2"}
],
city: "",
country: "USA",
description: "",
options: {transactionType: "test", desOptions: "not found"},
phone: "",
title: ""

I want to remove transactionType or desOptions from localStorage if it's empty.

Do you have a solution or idea?

You can try this:

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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