'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?



Solution 1:[1]

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

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sajeeb Ahamed