'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>
Solution 1:[1]
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);
}
}
Solution 2:[2]
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);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Meet |