Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do not delete all the keys of the localstorage

In my application I would like that in a moment all the keys of my localstorage will be deleted, with the exception of all the keys that contain the word "wizard".

Commands such as

localstorage.clear(); 

will erase everything, and I just want to keep those that have the word "wizard", I have tried in this way, but I get errors because if I delete a match, in the next iteration a key will be skipped, I will get the error that is trying to search a match in a position that will now be null, since it has been deleted. how can I solve that?

this is my code:

for ( var i = 0, len = localStorage.length; i < len; ++i ) {
  //if the key not contain the word "wizard" will be erased
  if( localStorage.getItem(localStorage.key(i)).search("wizard")==-1){
   localstorage.removeItem( localStorage.getItem( localStorage.key( i ) ) );
  }
}
like image 990
yavg Avatar asked Sep 01 '18 04:09

yavg


People also ask

How do I clear my local storage key?

To delete local storage sessions, use the removeItem() method. When passed a key name, the removeItem() method removes that key from the storage if it exists. If there is no item associated with the given key, this method will do nothing.

Which line of code deletes all data from localStorage?

The clear() method removes all the Storage Object item for this domain. The clear() method belongs to the Storage Object, which can be either a localStorage object or a sessionStorrage object.

What does localStorage Clear () do?

The clear() method of the Storage interface clears all keys stored in a given Storage object.

What is key in localStorage?

key() The key() method of the Storage interface, when passed a number n, returns the name of the nth key in a given Storage object.


1 Answers

You can iterate over the entries of localStorage, and delete the key if the value includes wizard:

localStorage.foo = 'foo';
localStorage.bar = 'wizard1';
localStorage.baz = 'wizard2';
localStorage.buzz = 'buzz';

Object.entries(localStorage).forEach(([key, val]) => {
  if (!val.includes('wizard')) delete localStorage[key];
});
console.log(Object.keys(localStorage));

Result: only bar and baz keys will remain.

(Cannot post as embedded snippet because stack snippets do not support localStorage)

https://jsfiddle.net/cLm3kg01/

If you want to keep key names which contain wizard rather than values that contain wizard, then use Object.keys instead of Object.entries to iterate over the keys:

localStorage.wizard1 = 'foo';
localStorage.wizard2 = 'bar';
localStorage.baz = 'baz';
localStorage.buzz = 'buzz';

Object.keys(localStorage).forEach((key) => {
  if (!key.includes('wizard')) delete localStorage[key];
});
console.log(Object.keys(localStorage));

https://jsfiddle.net/cLm3kg01/6/

like image 78
CertainPerformance Avatar answered Sep 28 '22 13:09

CertainPerformance