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?
If the browser supports HTML5 LocalStorage it should also implement Array.prototype.map, enabling this:
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:
We can also read by the name.
Say we have saved the value with name 'user' like this
Then we can read it by using
I used it and it is working smooth, no need to do the for loop
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):
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!)
You can use the localStorage.key(index) function to return the string representation.