By Simone


2011-12-07 17:04:00 8 Comments

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?

12 comments

@Ali Adravi 2016-05-26 13:32:43

We can also read by the name.

Say we have saved the value with name 'user' like this

localStorage.setItem('user', user_Detail);

Then we can read it by using

localStorage.getItem('user');

I used it and it is working smooth, no need to do the for loop

@Admir 2020-04-16 16:35:04

You can get keys and values like this:

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

@Rahim Naik 2019-08-14 10:25:30

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}`);
}

@nktshn 2019-07-06 12:44:01

in ES2017 you can use:

Object.entries(localStorage)

@user12834955 2020-03-12 00:30:52

and I assume Object.keys() works as expected as well?

@Jeffrey Sweeney 2011-12-07 17:08:07

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

@Mike Ratcliffe 2018-04-12 16:56:54

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 2018-04-20 09:43:08

@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.

@Darkrum 2018-04-20 14:05:30

Just read the spec for local storage and I do not see what you mentioned.

@Darkrum 2018-04-20 14:13:45

And read the spec for object.keys() looks like Firefox is what's not fallowing it if what you say is true.

@Mike Ratcliffe 2018-04-26 14:07:19

@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

@Darkrum 2018-04-27 19:58:34

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 2018-04-27 20:13:26

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 2018-04-27 20:29:44

And your method should fail also on Firefox seeing as they are not even allowing them to be set in the first place.

@Darkrum 2018-04-27 20:37:05

So with that being said you were infact wrong from the beginning and should just delete this answer instead of editing it.

@Mike Ratcliffe 2018-05-01 12:15:15

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/…

@cillay 2015-01-23 20:21:12

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);
})

@Lenny 2019-05-07 19:00:22

You can also do new Array(this.localStorage.length).fill(0) which feels a little less hacky than using apply imo.

@nerdcoder 2011-12-07 17:15:17

function listAllItems(){  
    for (i=0; i<=localStorage.length-1; i++)  
    {  
        key = localStorage.key(i);  
        alert(localStorage.getItem(key));
    }  
}

@Sean Colombo 2015-08-14 12:49:12

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!)

@Zack Argyle 2015-02-03 18:26:07

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;
}, {});

@Jonathan Stellwag 2018-08-31 08:01:41

I like that style of iterating over objects.

@Hassan Azimi 2015-02-03 12:30:59

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;
}

@Kevin Ennis 2011-12-07 17:13:27

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 ) ) );
}

@user1637281 2013-03-09 21:17:42

In this link .... stackoverflow.com/questions/15313606/… ... why are they using all these strange methods to access localStorage?

@apottere 2014-05-14 14:36:26

i < len: should be i < len;

@Luciano Bargmann 2014-08-31 18:25:57

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++?

@Kevin Ennis 2014-09-01 00:19:04

"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).

@Louis LC 2014-11-29 13:11:45

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...

@Kevin Ennis 2014-11-29 15:37:57

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.

@Adrian 2015-01-14 17:04:15

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.

@Sean Colombo 2015-08-14 12:43:54

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.

@Stijn de Witt 2015-09-02 09:24:55

+1 for the great update. The answer to OP's question indeed lies in Storage.key().

@akostadinov 2016-02-05 12:18:00

why is it unsafe to do for ... in? I thought dealing with indexes is much less safer from human errors

@Kevin Ennis 2016-02-24 02:05:44

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.

@Chris 2019-11-28 08:31:33

Why did you define variable len? It is not used in for loop.

@Viplav Soni 2020-08-05 14:03:19

Updated code print the data of local storage present for the key

Related Questions

Sponsored Content

22 Answered Questions

[SOLVED] Storing Objects in HTML5 localStorage

22 Answered Questions

[SOLVED] Checking if a key exists in a JavaScript object?

23 Answered Questions

[SOLVED] Get the current URL with JavaScript?

  • 2009-06-23 19:26:45
  • dougoftheabaci
  • 2864135 View
  • 3046 Score
  • 23 Answer
  • Tags:   javascript url

17 Answered Questions

[SOLVED] Change the selected value of a drop-down list with jQuery

41 Answered Questions

[SOLVED] How do I loop through or enumerate a JavaScript object?

39 Answered Questions

[SOLVED] How do you get a timestamp in JavaScript?

11 Answered Questions

[SOLVED] Clearing localStorage in javascript?

36 Answered Questions

[SOLVED] Change an HTML5 input's placeholder color with CSS

20 Answered Questions

Sponsored Content