Skip to content
Advertisement

How to remove one value from a key in localstorage that has many values?

I’ve seen this question asked before but the solutions didn’t help me hence why i’ve asked it again.

Currently, I am storing values into an array and that array is getting stored into localstorage.

This is the object

data.items -

0: {id: 190217270, node_id: 'MDEwOlJlcG9zaXRvcnkxOTAyMTcyNzA=', name: '3-Bit-CNC-Starter-Pack'}
1: {id: 187179414, node_id: 'MDEwOlJlcG9zaXRvcnkxODcxNzk0MTQ=', name: 'inb-go}

I have mapped through this and used ‘name’ as the value. I am calling this value through a button using this function

const favs = [];

  function checkId(e) {
    if (e.target.value !== ""){
      if (!favs.includes(e.target.value)){
      favs.push(e.target.value);
      localStorage.setItem("name", JSON.stringify(favs));
      console.log(favs);
      document.getElementById("favsarray").innerHTML = favs;
      }
    }
     
    }

and to remove the value from localstorage I am using this function.

function removeId(e, value) {
    if (e.target.value !== "") {
     
      favs.pop(e.target.value);
      console.log(favs);
      document.getElementById("favsarray").innerHTML = favs;
      const stored = JSON.parse(localStorage.getItem("name"));
      delete stored[value, e.target.value];
      localStorage.setItem("name", JSON.stringify(stored));
      console.log(stored);
      
    }
  }

Although the value is being removed from the array, it is not being removed from localstorage.

side note – I am calling this function with a separate button.

console log

array (item is gone)
[]

localstorage (the value is still there)
[
    "Spiral-Up-Cut-Router-Bit"
]

But if I select another item to be added to localstorage, then the previous item gets removed.

UNFAVORITE - FUNCTION REMOVEid
[
        "Spiral-Up-Cut-Router-Bit"
    ]

 NEW FAVORITE - FUNCTION NEWId

[
    "graphqless"
]

I hope this makes sense, I tried to add detail to it as best as possible.

Advertisement

Answer

Try to use localStorage.removeItem method to remove item from storage:

function removeId(e, value) {
   if (e.target.value !== "") {     
      favs.pop();
      // other code here

      localStorage.removeItem('name'); // method to remove item from storage
      
   }
}

UPDATE:

If an item is removed from array and we want to set this updated value to localstorage, then we can just update this value:

function removeId(e, value) {
   if (e.target.value !== "") {     
      favs.pop();
      console.log(favs);
      document.getElementById("favsarray").innerHTML = favs;
      const stored = JSON.parse(localStorage.getItem("name"));
      delete stored[value, e.target.value]; // this code looks very fishy - charlietfl

      localStorage.setItem("name", JSON.stringify(favs));

      console.log(stored);      
   }
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement