126

So, I was thinking I could just loop through localStorage like a normal object as it has a length. How can I loop through this?

localStorage.setItem(1,'Lorem');
localStorage.setItem(2,'Ipsum');
localStorage.setItem(3,'Dolor');

If I do a localStorage.length it returns 3 which is correct. So I'd assume a for...in loop would work.

I was thinking something like:

for (x in localStorage){
    console.log(localStorage[x]);
}

But no avail. Any ideas?

The other idea I had was something like

localStorage.setItem(1,'Lorem|Ipsum|Dolor')
var split_list = localStorage.getItem(1).split('|');

In which the for...in does work.

Dara Java
  • 2,410
  • 3
  • 27
  • 52
Oscar Godson
  • 31,662
  • 41
  • 121
  • 201

10 Answers10

174

You can use the key method. localStorage.key(index) returns the indexth key (the order is implementation-defined but constant until you add or remove keys).

for (var i = 0; i < localStorage.length; i++){
    $('body').append(localStorage.getItem(localStorage.key(i)));
}

If the order matters, you could store a JSON-serialized array:

localStorage.setItem("words", JSON.stringify(["Lorem", "Ipsum", "Dolor"]));

The draft spec claims that any object that supports structured clone can be a value. But this doesn't seem to be supported yet.

EDIT: To load the array, add to it, then store:

var words = JSON.parse(localStorage.getItem("words"));
words.push("hello");
localStorage.setItem("words", JSON.stringify(words));
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
  • Thanks a lot! This is just what I was looking for. Im going to look into the JSON thing you sent also. Thatd be perfect. It's for a Baby Names Offline HTML5 iOS app. – Oscar Godson Jun 29 '10 at 16:47
  • Quick question, how would I add to that JSON? Like, how would I add "hello" after "Dolor"? – Oscar Godson Jun 29 '10 at 16:51
  • @Oscar, I gave an example above. Basically, get, parse, modify the array, stringify, set. – Matthew Flaschen Jun 29 '10 at 20:17
  • 1
    you rock, just looking at, it should work. Is there a reason I should use parse and not eval? I'm using eval now to get it from a string, but is parse better/faster? – Oscar Godson Jun 29 '10 at 21:15
  • 1
    @Oscar, `parse` is more secure because it protects you from code execution. And often, it's also much faster. See http://blog.mozilla.com/webdev/2009/02/12/native-json-in-firefox-31/ – Matthew Flaschen Jun 29 '10 at 21:53
  • @MatthewFlaschen, @OscarGodson, parse is a method of the JSON object that is not Cross Browser as of now (not <= IE8 at least). But definitely, parse is faster & secure. Additionally, when you create a JSON object manually for say IE, you internally use eval. `eval("var p=" + str + ";");` - where `str` is what you want to parse – Om Shankar Jul 17 '12 at 07:14
  • @OmShankar, IE 8 does support native JSON, so I think you mean "< IE8" – Matthew Flaschen Jul 25 '12 at 02:58
  • @MatthewFlaschen, Oops, didn't know bout IE8's native support for JSON. Thanks – Om Shankar Jul 25 '12 at 10:01
  • Doesn't JSON.parse() return an object, in which case words.push() wouldn't work as .push is a method for arrays, not objects? – BBagi Apr 19 '13 at 17:02
  • 1
    @BBagi, it returns whatever the input is, decoded. The top level of a JSON text can be an object or array. Try `JSON.parse('["Lorem", "Ipsum", "Dolor"]').length` – Matthew Flaschen Apr 20 '13 at 04:39
61

The simplest way is:

Object.keys(localStorage).forEach(function(key){
   console.log(localStorage.getItem(key));
});
Putra Ardiansyah
  • 5,249
  • 4
  • 25
  • 37
  • This worked for me. using `$.each(localStorage, function(key, value)` for some reason included the localStorage functions (i.e cleaR) in the key list. – TheoretiCAL Feb 10 '21 at 20:15
  • @TheoretiCAL Probably because you've overwritten the prototype. – Tim Oct 20 '21 at 12:24
23

In addition to all the other answers, you can use $.each function from the jQuery library:

$.each(localStorage, function(key, value){

  // key magic
  // value magic

});

Eventually, get the object with:

JSON.parse(localStorage.getItem(localStorage.key(key)));

AnnanFay
  • 9,573
  • 15
  • 63
  • 86
miksiii
  • 2,426
  • 26
  • 22
  • 2
    This only works if you are using jQuery. `$` is used for other libraries and is also often used as an alias for `document.querySelectorAll`. The question is also not tagged as a [jquery] question. – AnnanFay Jul 06 '18 at 02:24
  • fails on build in key 'functions' like 'clear' etc... – sebhaase Jul 19 '22 at 16:31
11
for (const [key, value] of Object.entries(localStorage)) {
   console.log(key, value);
}

Here we are looping through each key and value respectively in local storage.

Wizard
  • 462
  • 1
  • 6
  • 14
9

This works for me in Chrome:

for(var key in localStorage) {
  $('body').append(localStorage.getItem(key));
}
WispyCloud
  • 4,140
  • 1
  • 28
  • 31
5

localStorage is an Object.

We can loop through it with JavaScript for/in Statement just like any other Object.

And we will use .getItem() to access the value of each key (x).

for (x in localStorage){
    console.log(localStorage.getItem(x));
}
Shayan
  • 709
  • 1
  • 15
  • 31
  • This routine will also return functions, not just properties, which is likely undesirable to most people wanting to get only the property keys and values from localStorage. – Volomike May 08 '22 at 23:46
4

Building on the previous answer here is a function that will loop through the local storage by key without knowing the key values.

function showItemsByKey() {
   var typeofKey = null;
   for (var key in localStorage) {
       typeofKey = (typeof localStorage[key]);
       console.log(key, typeofKey);
   }
}

If you examine the console output you will see the items added by your code all have a typeof string. Whereas the built-in items are either functions { [native code] } or in the case of the length property a number. You could use the typeofKey variable to filter just on the strings so only your items are displayed.

Note this works even if you store a number or boolean as the value as they are both stored as strings.

2

All of these answers ignore the differences between the implementations of localStorage across browsers. Contributors in this domain should heavily qualify their responses with the platforms they are describing. One browser-wide implementation is documented at https://developer.mozilla.org/en/docs/Web/API/Window/localStorage and, whilst very powerful, only contains a few core methods. Looping through the contents requires an understanding of the implementation specific to individual browsers.

Sailor Al
  • 797
  • 1
  • 7
  • 20
  • 1
    Could you give an example of how one of these answers would not work on a browser? This was a long time ago but I don't remember running into any issues with looping through with these answers – Oscar Godson Feb 12 '16 at 16:52
  • I intended my comment to be added to the overall stream, not this particular post and may have been a bit harsh. I was frustrated at the time trying to find a cross-browser solution. The example by Steve Isenberg (below) containing for (var key in localStorage) { typeofKey = (typeof localStorage[key]); console.log(key, typeofKey); } Doesn't work on webKit implementations (try it!) – Sailor Al Feb 14 '16 at 06:11
  • This does work: for ( var i = 0; i < localStorage.length; ++i ) { console.log(localStorage.key(i)+":"+ localStorage.getItem(localStorage.key(i))); } – Sailor Al Feb 14 '16 at 06:15
1

The localStorage saves data as key-value pairs and the values can be accessed by the function localStorage.getItem(key), which takes a key as parameter and returns the value of the key-value pair with the given key.

The key-value pairs of the localStorage can be set with the function localStorage.setItem(key, value).

If you want to iterate through the localStorage you can use numbers as keys.

localStorage.setItem(localStorage.length, value);

With this instruction above you are appending a value with an ascending key to the localStorage, because the length of the localStorage is increased by each call.

Now the localStorage can be iterated with the following for-loop.

for (let i = 0; i < localStorage.length; i++){
  console.log(localStorage.getItem(i));
} 

It does not matter if you use "let" or "var" to declare a variable. The difference between both is the scope. If you want to know more about the difference between let and var, I would recommend you the explanation by tutorialspoint (https://www.tutorialspoint.com/difference-between-var-and-let-in-javascript).

0

Get all the entries with key and value in Array

let entries = Object.entries(localStorage);

console.log(entries);
Surya R Praveen
  • 3,393
  • 1
  • 24
  • 25