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?
I like to create an easily visible object out of it like this.
I do a similar thing with cookies as well.
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 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:Because key, getItem and setItem are prototypal methods
Object.keys(localStorage)
will only return["key2"]
.You are best to do something like this: