Get HTML5 localStorage keys

JavascriptHtmlKeyLocal Storage

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

in ES2017 you can use:

Object.entries(localStorage)

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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

Solution 6 - Javascript

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

Solution 7 - Javascript

You can get keys and values like this:

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

Solution 8 - Javascript

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

Solution 9 - Javascript

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

Solution 10 - Javascript

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

Solution 11 - Javascript

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

Solution 12 - Javascript

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

Solution 13 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSimoneView Question on Stackoverflow
Solution 1 - JavascriptKevin EnnisView Answer on Stackoverflow
Solution 2 - JavascriptnktshnView Answer on Stackoverflow
Solution 3 - JavascriptZack ArgyleView Answer on Stackoverflow
Solution 4 - JavascriptnerdcoderView Answer on Stackoverflow
Solution 5 - JavascriptJeffrey SweeneyView Answer on Stackoverflow
Solution 6 - JavascriptcillayView Answer on Stackoverflow
Solution 7 - JavascriptAdmirView Answer on Stackoverflow
Solution 8 - JavascriptSean ColomboView Answer on Stackoverflow
Solution 9 - JavascriptAmir Hassan AzimiView Answer on Stackoverflow
Solution 10 - JavascriptRahimoddin NaikwadeView Answer on Stackoverflow
Solution 11 - JavascriptjknotekView Answer on Stackoverflow
Solution 12 - JavascriptAli Mert CakarView Answer on Stackoverflow
Solution 13 - JavascriptMike RatcliffeView Answer on Stackoverflow