199

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Simone
  • 20,302
  • 14
  • 79
  • 103
  • possible duplicate of [How can I show all the localStorage saved varliables?](http://stackoverflow.com/questions/5410820/how-can-i-show-all-the-localstorage-saved-varliables) – epascarello Dec 07 '11 at 17:11
  • 1
    possible duplicate of http://stackoverflow.com/questions/3138564/looping-through-localstorage-in-html5-and-javascript – kubetz Dec 07 '11 at 17:15
  • 1
    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... – Louis LC Nov 29 '14 at 13:09
  • 1
    @LouisLC because I was using progressive numbers for my keys (like a primary key in a relational database). – Simone Dec 03 '14 at 09:33

15 Answers15

337
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 ) ) );
}
Kevin Ennis
  • 14,226
  • 2
  • 43
  • 44
  • 1
    In this link .... http://stackoverflow.com/questions/15313606/ie8-and-localstorage-support/15313629#15313629 ... why are they using all these strange methods to access localStorage? –  Mar 09 '13 at 21:17
  • 1
    `i < len:` should be `i < len;` – apottere May 14 '14 at 14:36
  • 4
    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++`? – Luciano Bargmann Aug 31 '14 at 18:25
  • 1
    "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`). – Kevin Ennis Sep 01 '14 at 00:19
  • 1
    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... – Louis LC Nov 29 '14 at 13:11
  • 11
    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. – Kevin Ennis Nov 29 '14 at 15:37
  • 54
    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. – Adrian Jan 14 '15 at 17:04
  • 3
    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. – Sean Colombo Aug 14 '15 at 12:43
  • 1
    +1 for the great update. The answer to OP's question indeed lies in [Storage.key()](https://developer.mozilla.org/en-US/docs/Web/API/Storage/key). – Stijn de Witt Sep 02 '15 at 09:24
  • 1
    why is it unsafe to do `for ... in`? I thought dealing with indexes is much less safer from human errors – akostadinov Feb 05 '16 at 12:18
  • 1
    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 @Adrian mentioned, `Object.keys()` is safe in modern browsers. – Kevin Ennis Feb 24 '16 at 02:05
  • 1
    Why did you define variable `len`? It is not used in `for` loop. – Chris Nov 28 '19 at 08:31
  • 1
    Updated code print the data of local storage present for the key – Viplav Soni Aug 05 '20 at 14:03
  • `for...in` also returns the methods on `localStorage` for me (e.g. `getItem`, `setItem`). Use `Object.keys` instead. – Ryan Feb 08 '22 at 17:07
  • Wow, thanks for updating your answer so many years later. – Emperor Eto Jun 07 '22 at 16:01
88

in ES2017 you can use:

Object.entries(localStorage)
nktshn
  • 1,047
  • 7
  • 6
  • 19
    and I assume `Object.keys()` works as expected as well? –  Mar 12 '20 at 00:30
  • 2
    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()` – Rifton007 Jul 29 '21 at 00:05
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;
}, {});
Zack Argyle
  • 8,057
  • 4
  • 29
  • 37
20
function listAllItems(){  
    for (i=0; i<localStorage.length; i++)  
    {  
        key = localStorage.key(i);  
        alert(localStorage.getItem(key));
    }  
}
Pawel Cioch
  • 2,895
  • 1
  • 30
  • 29
nerdcoder
  • 399
  • 2
  • 8
11

You can get keys and values like this:

for (let [key, value] of Object.entries(localStorage)) {
  console.log(`${key}: ${value}`);
}
Admir
  • 2,876
  • 1
  • 19
  • 19
10

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

kendaleiv
  • 5,793
  • 3
  • 28
  • 38
Jeffrey Sweeney
  • 5,986
  • 5
  • 24
  • 32
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);
})
Bruno
  • 6,623
  • 5
  • 41
  • 47
cillay
  • 81
  • 1
  • 1
  • 2
    You can also do `new Array(this.localStorage.length).fill(0)` which feels a little less hacky than using apply imo. – Lenny May 07 '19 at 19:00
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!)

Sean Colombo
  • 1,459
  • 17
  • 24
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}`);
}
3

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

The answer is simply:

Object.keys(localStorage);
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Tomas
  • 3,054
  • 5
  • 27
  • 39
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;
}
Amir Hassan Azimi
  • 9,180
  • 5
  • 32
  • 43
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).

jknotek
  • 1,778
  • 2
  • 15
  • 23
0

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

$.each(localStorage, function(key, str){
  console.log(key + ": " + str);
});
Twisty
  • 30,304
  • 2
  • 26
  • 45
-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));
}
Mike Ratcliffe
  • 989
  • 6
  • 10
  • 1
    @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. – Mike Ratcliffe Apr 20 '18 at 09:43
  • 1
    Just read the spec for local storage and I do not see what you mentioned. – Darkrum Apr 20 '18 at 14:05
  • 1
    And read the spec for object.keys() looks like Firefox is what's not fallowing it if what you say is true. – Darkrum Apr 20 '18 at 14:13
  • 1
    @Darkrum Look at https://html.spec.whatwg.org/multipage/webstorage.html#the-storage-interface 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: https://github.com/whatwg/html/issues/183 – Mike Ratcliffe Apr 26 '18 at 14:07
  • 1
    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. – Darkrum Apr 27 '18 at 19:58
  • 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. – Darkrum Apr 27 '18 at 20:13
  • And your method should fail also on Firefox seeing as they are not even allowing them to be set in the first place. – Darkrum Apr 27 '18 at 20:29
  • So with that being said you were infact wrong from the beginning and should just delete this answer instead of editing it. – Darkrum Apr 27 '18 at 20:37
  • 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 https://html.spec.whatwg.org/multipage/webstorage.html#the-storage-interface – Mike Ratcliffe May 01 '18 at 12:15
-1

Just type localStorage to developer console. It logs localStorage keys nicely formatted. Sometimes the easiest answer is the best one :)

Ali Mert Çakar
  • 290
  • 1
  • 8
  • 15