Home > Back-end >  Remove all localstorage items with the value true?
Remove all localstorage items with the value true?

Time:05-05

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 >one</div>
<br>
<div >clear</div>

CodePudding user response:

You can retrieve all localStorage items with

const localStorageObj = { ...localStorage };

Get list of keys:

const localStorageKeys = Object.keys(localStorageObj);

Check where value is true and remove:

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

CodePudding user response:

First you need all keys from localStorage then you can iterate over.

const keys = Object.keys(localStorage)

keys.forEach(l => {
  if (l[key] == true) {
    localStorage.removeIteml(l[key]);    
  }
})

  • Related