Lowis
Lowis

Reputation: 123

Remove all localstorage items with the value true?

I'd like to reset localstorage daily and remove a lot of the old storage but also keep a few important items for some users (localStorage.clear() not an option).

The keys I'd like removed all have the value true. The important items to keep have different values. Rather than listing every single item (200+) that I want to remove do you think it's possible to remove all at once by targeting the value of true?

As you can see from this JSfiddle example the one button adds three items to local storage and two of them have the true value.

$(".no").on('click', function() {
  localStorage.removeItem(true)
});

$(".one").on('click', function() {
  localStorage.setItem("one", true)
  localStorage.setItem("two", "yes")
  localStorage.setItem("three", true)
});
.no {
  width: 40px;
  padding: 10px 40px;
  border: 2px solid black;
}

.one {
  width: 40px;
  padding: 10px 40px;
  border: 2px solid black;
}
<div class="one">one</div>
<br>
<div class="no">clear</div>

Upvotes: 0

Views: 98

Answers (2)

Meet
Meet

Reputation: 344

You can try with the below code.

    const localStorageKeys = Object.keys(localStorage);
      for (let key of localStorageKeys) {
        /*Also check with True as well if value is added like this  */
       if (localStorage[key] === "true" || localStorage[key] === "True") {
        console.log(key);
       }
     }

Upvotes: 1

Filip Kučanda
Filip Kučanda

Reputation: 51

Get list of item keys from localStorage:

const localStorageKeys = Object.keys(localStorage);

Check where value is true and remove:

for (let key of localStorageKeys) {
  if (localStorage[key] === "true") {
    localStorage.removeItem(key);
  }
}

Upvotes: 1

Related Questions