19

Is it not posssible to retrieve all keys/objects that I stored in sessionStorage (or localStorage)?

If I have done sessionStorage.name = 'John' and sessionStorage.city = 'New York', isn't there a way to get a list that shows the keys name and city?

TheStoryCoder
  • 3,403
  • 6
  • 34
  • 64

5 Answers5

30

to get a list that shows the keys name and city

Use Object.keys() function:

sessionStorage.name = 'John';
sessionStorage.city = 'New York';

console.log(Object.keys(sessionStorage));
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
6

You can use the Object.keys() and reduce():

var obj = Object.keys(localStorage).reduce(function(obj, key) {
   obj[key] = localStorage.getItem(key);
   return obj
}, {});

console.log(obj)
user7693832
  • 6,119
  • 19
  • 63
  • 114
2

With this you can assign all the data in local storage into an object:

let storage = {}
Object.keys(localStorage).forEach((key) => {
    storage[key] = localStorage.getItem(key);
});
1

If you don't need to support IE9 or less (or are happy to use a Polyfills than you can use a combination of Object.keys() and Array. prototype.map() as follows:

Object.keys(localStorage).map(function(c,i,a){
  // do whatever
});

The Object.keys() returns an array of the enumerable values of the object passed to it with the added benefit of not enumerating through any properties in its prototype chain.

You can then run operations over this returned array with Array.prototype.map().

Pineda
  • 7,435
  • 3
  • 30
  • 45
0

You can get the keys and their values as such.

for (const [key, value] of Object.entries(sessionStorage)) {
    console.log({key, value});
};

this should work except IE11