Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a list of the items stored in html 5 local storage from javascript?

How can I get a list of the items stored in html 5 local storage from javascript?

like image 684
Kyle Avatar asked Mar 23 '11 19:03

Kyle


People also ask

How do I display local storage data in HTML?

“how to display local storage data in html” Code Answer's Just go to the developer tools by pressing F12 , then go to the Application tab. In the Storage section expand Local Storage. After that, you'll see all your browser's local storage there.

How do I see my localStorage items?

To check if a key exists or not in localStorage, we can use the localStorage. getItem() method. The localStorage. getItem() method takes the key as an argument and returns the key's value.

How do I get items from local storage array?

Get Array From localStorage If you want to retrieve the array from the local storage, you can use the getItem method. The method takes only one parameter, the "key", and returns the "value" in a string format. The last line of code retrieves the array from the local storage and converts it from a string to an array.


5 Answers

From HTML5 reference:

Like other JavaScript objects, you can treat the localStorage object as an associative array. Instead of using the getItem() and setItem() methods, you can simply use square brackets.

localStorage.setItem('test', 'testing 1');
localStorage.setItem('test2', 'testing 2');
localStorage.setItem('test3', 'testing 3');

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

//test for firefox 3.6 see if it works
//with this way of iterating it
for(var i=0, len=localStorage.length; i<len; i++) {
    var key = localStorage.key(i);
    var value = localStorage[key];
    console.log(key + " => " + value);
}

This will output:

testing 3
testing 2
testing 1

test3 => testing 3
test2 => testing 2
test => testing 1

Here is the JSFiddle Demo

like image 88
KJYe.Name Avatar answered Sep 29 '22 22:09

KJYe.Name


localStorage is reference to object window.Storage, so u can use it as each other object:

Get array of items

Object.keys(localStorage)

Get length

Object.keys(localStorage).length

Iterate with jquery

$.each(localStorage, function(key, value){
   .....
})
like image 27
Richard Hutta Avatar answered Sep 29 '22 22:09

Richard Hutta


What about:

Object.keys(localStorage).map(k => localStorage.getItem(k))
like image 45
Pavel Durov Avatar answered Sep 29 '22 22:09

Pavel Durov


you can use Object.assign():

var data = Object.assign({}, localStorage)
like image 20
Yukulélé Avatar answered Sep 29 '22 22:09

Yukulélé


Since localStorage is key-value with strings, just serialize it with JSON, and deserialize it when you want to retrieve it.

 localStorage.setItem("bar", JSON.stringify([1,2,3]));
 var foo = localStorage.getItem("bar");
 JSON.parse(foo);
 // returns [1,2,3]
like image 40
Mike Lewis Avatar answered Sep 29 '22 22:09

Mike Lewis