Home > Software engineering >  How to remove one value from a key in localstorage that has many values?
How to remove one value from a key in localstorage that has many values?

Time:02-08

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.

CodePudding user response:

The easiest way is to just overwrite the item in localStorage. Once you remove the item from the favs array, call localStorage.setItem("name", JSON.stringify(favs)); again and you're done.

CodePudding user response:

Try to use Delete operation on array

You can refer to the above output image, when I deleted the array values using the value even though its output is true it does not delete the value from the array. But when I used the index value for the delete, it deleted the value from the array.

Note: The array just removed the value but did not clear the index.

Maybe, you should use splice to remove specific values from the array and store the new array into the storage.

Also, the delete operator works well with JS objects. If you want to read more about this you can go to this enter image description here

  •  Tags:  
  • Related