J. Chase
J. Chase

Reputation: 1413

Return all localStorage in 1 Object?

How would it be possible to return an object containing all localStorage keys/values? Mainly to future-proof code as best as possible, rather than declaring known keys to store, I'm looking for a way to get everything.

For context: This will be used in a Chrome extension to synchronize preferences.

Upvotes: 4

Views: 628

Answers (2)

Dallas
Dallas

Reputation: 542

If you wanted to do that, you could simply loop through each item, and append the current item, separated by a space.

var allkeys = ""; ;
for (i=0;i < localStorage.length;i++) {
    var key = localStorage.key(i);
    allkeys += key + " " + localStorage.getItem(key) + " ";
}

I put a space between each key and value so that you can use a Tokenizer or something similar to break apart using spaces as delimiters. You could add in a "Key"+i and/or "value"+i descriptor in front of each item to aid in parsing or looking for an item without having to loop through keys to find the matching one.

Upvotes: 3

F&#233;lix Saparelli
F&#233;lix Saparelli

Reputation: 8719

Why would you want to do that? Besides, localStorage is an object, which contains all key:value pairs stored by the browser. If you want to copy it, you should loop through its properties.

What it looks like you want/need, though, is a wrapper that will abstract away the localStorage insterface, so you if you would change the way you store your data later, you would only need to change this wrapper without your code noticing any difference. I do that myself.

There are several libraries which achieve this with varying levels of complexity and/or functionality. For example, jStorage lets you use userData in IE if localStorage isn't available. My own Storage.js only wraps localStorage but has methods to act on multiple items at once.

Upvotes: 0

Related Questions