4

Let's say my localStorage looks something like this.

item1: 123,
item2: 124,
token: 5487354787

Is there any way I can do something like localStorage.removeItem('123') instead of having to do localStorage.removeItem("item1")?

Philipp Maurer
  • 2,480
  • 6
  • 18
  • 25
Kuda
  • 95
  • 1
  • 9
  • 1
    You can loop through localStorage and delete: [HTML5 localStorage getting key from value](https://stackoverflow.com/questions/12949723) (That question is closed and Danziger's answer is much better) – adiga May 06 '20 at 05:31

1 Answers1

6

You can iterate over all entries in localStorage using Object.entries():

function removeLocalStorageValue(targetValue) {
  Object.entries(localStorage).forEach(([key, value]) => {
    if (value === targetValue) localStorage.removeItem(key);
  });
}

Alternatively, the same can be done with Object.keys():

function removeLocalStorageValue(targetValue) {
  Object.keys(localStorage).forEach((key) => {
    if (localStorage.getItem(key) === targetValue) localStorage.removeItem(key);
  });
}
Danziger
  • 19,628
  • 4
  • 53
  • 83