Sunil Kumar
Sunil Kumar

Reputation: 420

Clear session storage data with retrieving the specified session storage item

I have to clear the session with retrieving the specific item.

there are lot of session items to clear but apart from one cart item

now i am doing like this to retrieve the cart value in session storage

var cart = window.sessionStorage.getItem('cart');
window.sessionStorage.clear();
window.sessionStorage.setItem('cart', cart);

for it's working fine, now i have to retrieve 7 different items (there are more than 40 session items present in my session),

is there any good way to achieve the same?

Note: i have only retrieve items keys like ['cart' 'user' 'logTime'] but not clear item keys

Upvotes: 1

Views: 1837

Answers (2)

Oleksandr Paiziak
Oleksandr Paiziak

Reputation: 382

You can create array of keys what you want to remove

['key1', 'key2'].forEach((key) => {
  window.sessionStorage.removeItem(key)
});

if your list is to big you can create separate variable with all keys const storageKeys = ['key1', 'key2', etc...]; and storageKeys.forEach(....

Editing according to last comments

const savedData = []; 
['key1', 'key2'].forEach((key) => { 
  savedData.push([key, window.sessionStorage.getItem(key)]); 
}); 
window.sessionStorage.clear(); 
savedData.forEach(([key, value]) => window.sessionStorage.setItem(key, value));

Upvotes: 1

Omri Attiya
Omri Attiya

Reputation: 4037

You can create a function to retrieve the desired session storage item and remove only that specific item, and not the entire storage:

function getStorageItem(itemKey) {
  let item = window.sessionStorage.getItem(itemKey);
  window.sessionStorage.removeItem(itemKey);
  return item;
}

Upvotes: 0

Related Questions