Get HTML5 localStorage keys
Asked Answered
L

15

205

I'm just wondering how to get all key values in localStorage.


I have tried to retrieve the values with a simple JavaScript loop

for (var i=1; i <= localStorage.length; i++)  {
   alert(localStorage.getItem(i))
}

But it works only if the keys are progressive numbers, starting at 1.


How do I get all the keys, in order to display all available data?

Luftwaffe answered 7/12, 2011 at 17:4 Comment(4)
possible duplicate of How can I show all the localStorage saved varliables?Frechette
possible duplicate of #3139064Summerly
Why does this loop start with i = 1 and end with i = localStorage.length? In the browsers I've tested (Chrome), the loop should start at 0 and end at localStorage.length - 1...Epiboly
@LouisLC because I was using progressive numbers for my keys (like a primary key in a relational database).Luftwaffe
T
94

in ES2017 you can use:

Object.entries(localStorage)
Tantra answered 6/7, 2019 at 12:44 Comment(3)
and I assume Object.keys() works as expected as well?Sardonyx
It is not correct, that return key and values and the title of this post is "Get HTML5 localStorage keys". The corret response is above Object.keys()Coir
it doesn't seem to work for the key key => localStorage.setItem("key", "value"), Object.entries(localStorage) returns [], Object.keys(localStorage) returns ["key"]Varro
C
340
for (var key in localStorage){
   console.log(key)
}

EDIT: this answer is getting a lot of upvotes, so I guess it's a common question. I feel like I owe it to anyone who might stumble on my answer and think that it's "right" just because it was accepted to make an update. Truth is, the example above isn't really the right way to do this. The best and safest way is to do it like this:

for ( var i = 0, len = localStorage.length; i < len; ++i ) {
  console.log( localStorage.getItem( localStorage.key( i ) ) );
}
Crossley answered 7/12, 2011 at 17:13 Comment(15)
In this link .... #15314106 ... why are they using all these strange methods to access localStorage?Bricky
i < len: should be i < len;Shad
Several questions for the "best/safest" code: 1) Why declare localStorage.length and not use it directly? 2) Why declare it inside the for loop? 3) Why ++i is preferred over i++?Auditor
"Safest" was really in reference to not using a for ... in loop, not the mechanics my for loop. But since you asked... caching length is just a habit. It's usually faster, so that's what I always do. Realistically, the performance benefit is probably negligible – but it doesn't hurt. ++i vs i++ is just personal preference. The postfix increment operator always seems a little weird to me, since it increments the number immediately but evaluates to whatever the number was prior to being incremented (so in i = 7; j = i++;, j is 7, not 8).Crossley
Regarding the "++i" : this makes the loop start at i=1 and end at i=localStorage.length, but in the browsers I've tested (Chrome), the loop should start at 0 and end at localStorage.length-1...Epiboly
Did you actually try it? ++i most definitely does not make the loop start at i = 1. The third expression inside the parenthesis is evaluated after each iteration. i++ and ++i both have the exact same effect on i. The difference is that ++i evaluates to the new value of i after incrementing, whereas i++ evaluates to the value of i before incrementing. It makes absolutely no difference here, because all we care about is the side-effect of incrementing i, not the value of the expression.Crossley
It's worth noting that nowadays Object.keys(localStorage) works perfectly well for this scenario, as long as you don't need to support IE < 9.Pupa
Also useful to note is that if you want to display the name of the key itself, you can do that with the localStorage.key( i ) part.Diaconicon
+1 for the great update. The answer to OP's question indeed lies in Storage.key().Vogue
why is it unsafe to do for ... in? I thought dealing with indexes is much less safer from human errorsBrutalize
I think at the time that I wrote the update to my answer, I was probably thinking of inherited properties or length. Not sure if old IE correctly marks those as non-enumerable. If it doesn't, they'd show up in your for...in loop. Modern browsers all deal with this correctly, and maybe old versions of IE do too, but I'm not 100% sure. Basically, localStorage has a length property and numeric indexes via key() – which sort of leads me to believe that the "preferred" iteration pattern is a for loop. All of that said, as @Pupa mentioned, Object.keys() is safe in modern browsers.Crossley
Why did you define variable len? It is not used in for loop.Nena
Updated code print the data of local storage present for the keyBrannon
for...in also returns the methods on localStorage for me (e.g. getItem, setItem). Use Object.keys instead.Gaal
Wow, thanks for updating your answer so many years later.Scaffolding
T
94

in ES2017 you can use:

Object.entries(localStorage)
Tantra answered 6/7, 2019 at 12:44 Comment(3)
and I assume Object.keys() works as expected as well?Sardonyx
It is not correct, that return key and values and the title of this post is "Get HTML5 localStorage keys". The corret response is above Object.keys()Coir
it doesn't seem to work for the key key => localStorage.setItem("key", "value"), Object.entries(localStorage) returns [], Object.keys(localStorage) returns ["key"]Varro
F
34

I like to create an easily visible object out of it like this.

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

I do a similar thing with cookies as well.

document.cookie.split(';').reduce(function(obj, str){ 
    var s = str.split('='); 
    obj[s[0].trim()] = s[1];
    return obj;
}, {});
Franni answered 3/2, 2015 at 18:26 Comment(1)
I like that style of iterating over objects.Selfcongratulation
P
20
function listAllItems(){  
    for (i=0; i<localStorage.length; i++)  
    {  
        key = localStorage.key(i);  
        alert(localStorage.getItem(key));
    }  
}
Priesthood answered 7/12, 2011 at 17:15 Comment(1)
If using happy-dom for testing, this might be the best alternative because Object.keys(localStorage) has a bug on it github.com/capricorn86/happy-dom/issues/1181Bilabiate
M
13

You can get keys and values like this:

for (let [key, value] of Object.entries(localStorage)) {
  console.log(`${key}: ${value}`);
}
Macroscopic answered 16/4, 2020 at 16:35 Comment(0)
W
10

You can use the localStorage.key(index) function to return the string representation, where index is the nth object you want to retrieve.

Winkle answered 7/12, 2011 at 17:8 Comment(0)
M
8

If the browser supports HTML5 LocalStorage it should also implement Array.prototype.map, enabling this:

Array.apply(0, new Array(localStorage.length)).map(function (o, i) {
    return localStorage.key(i);
})
Mendelson answered 23/1, 2015 at 20:21 Comment(1)
You can also do new Array(this.localStorage.length).fill(0) which feels a little less hacky than using apply imo.Berkman
D
7

Since the question mentioned finding the keys, I figured I'd mention that to show every key and value pair, you could do it like this (based on Kevin's answer):

for ( var i = 0, len = localStorage.length; i < len; ++i ) {
  console.log( localStorage.key( i ) + ": " + localStorage.getItem( localStorage.key( i ) ) );
}

This will log the data in the format "key: value"

(Kevin: feel free to just take this info into the your answer if you want!)

Diaconicon answered 14/8, 2015 at 12:49 Comment(0)
S
4

For anyone searching this trying to find localStorage keys...

The answer is simply:

Object.keys(localStorage);
Sift answered 3/12, 2022 at 22:9 Comment(0)
P
3

This will print all the keys and values on localStorage:

ES6:

for (let i=0; i< localStorage.length; i++) {
    let key = localStorage.key(i);
    let value = localStorage[key];
    console.log(`localStorage ${key}:  ${value}`);
}
Pasadis answered 14/8, 2019 at 10:25 Comment(0)
P
2

I agree with Kevin he has the best answer but sometimes when you have different keys in your local storage with the same values for example you want your public users to see how many times they have added their items into their baskets you need to show them the number of times as well then you ca use this:

var set = localStorage.setItem('key', 'value');
var element = document.getElementById('tagId');

for ( var i = 0, len = localStorage.length; i < len; ++i ) {
  element.innerHTML =  localStorage.getItem(localStorage.key(i)) + localStorage.key(i).length;
}
Philosophize answered 3/2, 2015 at 12:30 Comment(0)
D
1

You can create an object even more simply by using Object.assign:

// returns an object of all keys/values in localStorage
Object.assign({}, window.localStorage);

You can read more about it here at MDN.

The caniuse page says support is currently at about 95% of all browser share (IE being the odd one out-- what a surprise).

Dennard answered 6/8, 2021 at 19:57 Comment(0)
R
0

For anyone looking for a jQuery solution, here is a quick example.

$.each(localStorage, function(key, str){
  console.log(key + ": " + str);
});
Rupiah answered 13/7, 2022 at 21:29 Comment(0)
O
-1

For those mentioning using Object.keys(localStorage)... don't because it won't work in Firefox (ironically because Firefox is faithful to the spec). Consider this:

localStorage.setItem("key", "value1")
localStorage.setItem("key2", "value2")
localStorage.setItem("getItem", "value3")
localStorage.setItem("setItem", "value4")

Because key, getItem and setItem are prototypal methods Object.keys(localStorage) will only return ["key2"].

You are best to do something like this:

let t = [];
for (let i = 0; i < localStorage.length; i++) {
  t.push(localStorage.key(i));
}
Oculist answered 12/4, 2018 at 16:56 Comment(9)
@Darkrum Because Firefox follows the spec correctly, key, getItem and setItem would be missing if you use object.keys()... I will update my answer to reflect that.Oculist
Just read the spec for local storage and I do not see what you mentioned.Sheepshanks
And read the spec for object.keys() looks like Firefox is what's not fallowing it if what you say is true.Sheepshanks
@Sheepshanks Look at html.spec.whatwg.org/multipage/… and you can see that the spec defines the IDL with [Exposed=Window]. This results in the behaviour I describe. If it was specified with [Exposed=Window,OverrideBuiltins] it would give the behaviour we expect but the spec doesn't specify OverrideBuiltins. You can see a discussion about it in whatwg/html here: github.com/whatwg/html/issues/183Oculist
Again as I will state this has nothing to do with how object.keys works. Mozillas choice to not allow them to be set is how they interpreted the spec. Clearly Google knew what it was doing because what does a prototype that can not be changed unless specifically done so through other means have anything to do with own properties.Sheepshanks
And your objection to using object.keys as a method to return all keys in localstorage is what at issue here because Mozilla said hey we won't allow setting these names because they exist on the Prototype chain (which is completely ridiculous) so guess what you do to get around mozzilas short sightedness? YOU USE A DIFFERENT KEY NAME. There is nothing wrong with object.keys. please edit your answer to state while object.keys is a perfectly good method there's this quirk in Firefox you should be aware of but that you can still use object.keys regardless.Sheepshanks
And your method should fail also on Firefox seeing as they are not even allowing them to be set in the first place.Sheepshanks
So with that being said you were infact wrong from the beginning and should just delete this answer instead of editing it.Sheepshanks
I just spelled it out even including a whatwg issue on the subject. I never said they can't be set, they can but the IDL does not include OverrideBuiltins, which means object.keys() should NOT include property names that exist on the prototype. If you wish to discuss this further you are welcome to contribute to html.spec.whatwg.org/multipage/…Oculist
Z
-2

Type localStorage to developer console. It logs localStorage keys nicely formatted.

Zelmazelten answered 1/10, 2021 at 22:32 Comment(2)
This is exactly what the OP was not looking for. Please actually read the question and have an understanding of the reqs before answeringIllusion
op asks "display localStorage". this displays local storage. (and displays it better formatted than application>local storage tab of browser dev tools imo)Benilda

© 2022 - 2024 — McMap. All rights reserved.