208

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?

4

15 Answers 15

342
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 ) ) );
}
15
  • 1
    In this link .... stackoverflow.com/questions/15313606/… ... why are they using all these strange methods to access localStorage?
    – user1637281
    Commented Mar 9, 2013 at 21:17
  • 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++? Commented Aug 31, 2014 at 18:25
  • 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. Commented Nov 29, 2014 at 15:37
  • 55
    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
    Commented Jan 14, 2015 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. Commented Aug 14, 2015 at 12:43
96

in ES2017 you can use:

Object.entries(localStorage)
3
  • 19
    and I assume Object.keys() works as expected as well?
    – user12834955
    Commented Mar 12, 2020 at 0: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
    Commented Jul 29, 2021 at 0:05
  • it doesn't seem to work for the key key => localStorage.setItem("key", "value"), Object.entries(localStorage) returns [], Object.keys(localStorage) returns ["key"] Commented Oct 25, 2023 at 16:29
35

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;
}, {});
1
  • 3
    I like that style of iterating over objects. Commented Aug 31, 2018 at 8:01
20
function listAllItems(){  
    for (i=0; i<localStorage.length; i++)  
    {  
        key = localStorage.key(i);  
        alert(localStorage.getItem(key));
    }  
}
1
13

You can get keys and values like this:

for (let [key, value] of Object.entries(localStorage)) {
  console.log(`${key}: ${value}`);
}
10

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

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);
})
1
  • 2
    You can also do new Array(this.localStorage.length).fill(0) which feels a little less hacky than using apply imo.
    – Lenny
    Commented May 7, 2019 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!)

4

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

The answer is simply:

Object.keys(localStorage);
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}`);
}
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;
}
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).

0

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

$.each(localStorage, function(key, str){
  console.log(key + ": " + str);
});
-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));
}
9
  • 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. Commented Apr 20, 2018 at 9:43
  • 1
    Just read the spec for local storage and I do not see what you mentioned.
    – Darkrum
    Commented Apr 20, 2018 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
    Commented Apr 20, 2018 at 14:13
  • 1
    @Darkrum 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/183 Commented Apr 26, 2018 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
    Commented Apr 27, 2018 at 19:58
-3

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

2
  • 1
    This is exactly what the OP was not looking for. Please actually read the question and have an understanding of the reqs before answering Commented Oct 29, 2023 at 21:05
  • op asks "display localStorage". this displays local storage. (and displays it better formatted than application>local storage tab of browser dev tools imo) Commented Oct 30, 2023 at 10:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.