'How to remove object from local storage

This is my code i want to remove https://prnt.sc/j9Un7C5nxDCZ custom pack 1 object from localstorage i tried removeitem() but its not deleting my object

var all_pack = JSON.parse(localStorage.getItem("CartItems"));

var object_length = Object.keys(all_pack).length;

var selected_option = "custom meal pack-1";

for (var i = 0; i < object_length; i++) {
  var p = Object.keys(all_pack)[i];
  if (selected_option === p) {
    Object.keys(all_pack)[i].removeItem();
  }
}


Solution 1:[1]

A storage stores strings. You have to read the string, parse it, modify it, serialize it and write it back.

Your code snippet lets me assume, that you don't want to remove an item from storage, but to delete a property from an object, that is stored in the local storage.

const all_pack = JSON.parse(localStorage.getItem("CartItems"));

const selected_option = "custom meal pack-1";

for (key in all_pack) {
  if (selected_option === key) {
    delete all_pack[key];
  }
}

// update local storage
// localStorage.setItem("CartItems", JSON.stringify(all_pack));

Example:

const all_pack = JSON.parse('{ "custom meal pack-1": true, "custom meal pack-2": true}');
    
const selected_option = "custom meal pack-1";
    
for (key in all_pack) {
  if (selected_option === key) {
    delete all_pack[key];
  }
}

console.log(all_pack);

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