Javascript: Retrieve all keys from sessionStorage?
Asked Answered
C

5

21

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?

Cloverleaf answered 24/1, 2017 at 10:55 Comment(1)
this may be useful https://mcmap.net/q/126743/-get-html5-localstorage-keysDoublereed
P
31

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));
Photomicrograph answered 24/1, 2017 at 11:6 Comment(0)
S
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)
Skep answered 9/4, 2018 at 7:39 Comment(0)
T
3

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);
});
Tercet answered 30/9, 2020 at 21:55 Comment(0)
S
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().

Searching answered 24/1, 2017 at 11:5 Comment(0)
C
1

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

Cologarithm answered 11/1, 2021 at 10:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.