What is the way to export the contents of localStorage
as a string and remove specific key-value pairs from it?
Namely, I need to preserve only those keys which values are like
or dislike
. Other keys should be removed.
In other words, the resulting string should be
"anne":"dislike","jane":"like","john":"like","mike":"dislike"
// the order doesn't matter
localStorage.clear();
localStorage.setItem('anne', 'dislike');
localStorage.setItem('jane', 'like');
localStorage.setItem('john', 'like');
localStorage.setItem('mike', 'dislike');
localStorage.setItem('abcd', 'foo');
localStorage.setItem('efgh', 'bar');
// this may be useful for something . . .
const stringified = JSON.stringify(localStorage);
Object.keys(localStorage).forEach(function(key) {
const value = localStorage.getItem(key);
if (value === 'like' || value === 'dislike') {
// what should be here?
}
});
I spent a day trying solutions from the following links:
- Removing specific item from localStorage
- How to delete a specific item/object in localStorage?
- Looping through localStorage in HTML5 and JavaScript
- How to retrieve all localStorage items without knowing the keys in advance?
- LocalStorage and JSON.stringify JSON.parse
But I still couldn't figure it out.
I don't want to change the original contents of local Storage
. I just want to export it as a "clean" string.