Kyle
Kyle

Reputation: 22035

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?

Upvotes: 56

Views: 75094

Answers (6)

Lucas D
Lucas D

Reputation: 465

You can use the localStorage as a plain object but it's not reccomended.

Here is a safer solution:

for (let i = 0; i < localStorage.length; i++) {
    const key = localStorage.key(i);
    const value = localStorage.getItem(key);
    console.log({key, value})
}

Upvotes: 0

Pavel Durov
Pavel Durov

Reputation: 1297

What about:

Object.keys(localStorage).map(k => localStorage.getItem(k))

Upvotes: 4

Yukul&#233;l&#233;
Yukul&#233;l&#233;

Reputation: 17062

you can use Object.assign():

var data = Object.assign({}, localStorage)

Upvotes: 6

Richard Hutta
Richard Hutta

Reputation: 679

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

Upvotes: 32

KJYe.Name
KJYe.Name

Reputation: 17169

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

Upvotes: 72

Mike Lewis
Mike Lewis

Reputation: 64137

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]

Upvotes: 2

Related Questions