Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through localStorage in HTML5 and JavaScript

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.

like image 435
Oscar Godson Avatar asked Jun 29 '10 07:06

Oscar Godson


People also ask

Can you loop through local storage?

There are multiple ways available to iterate through all keys stored in a localStorage object by using JavaScript. The above code snippet iterates over all keys stored in localStorage , and prints them on the console.

Can JavaScript access local storage?

There are four basic JavaScript methods you can use to access and work with localStorage: setItem() - takes a key-value pair and adds it to localStorage. getItem() - takes a key and returns the corresponding value. removeItem() - takes a key and removes the corresponding key-value pair.

Can we store JavaScript object in localStorage?

In summary, we can store JavaScript objects in localStorage by first converting them to strings with the JSON. stringify method, then back to objects with the JSON. parse method.


2 Answers

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)); 
like image 188
Matthew Flaschen Avatar answered Oct 05 '22 18:10

Matthew Flaschen


The simplest way is:

Object.keys(localStorage).forEach(function(key){    console.log(localStorage.getItem(key)); }); 
like image 31
Putra Ardiansyah Avatar answered Oct 05 '22 19:10

Putra Ardiansyah