Return all localStorage to 1 object?

How can I return an object containing all the keys / values ​​of localStorage? Basically, for the future code, it’s best, rather than declaring known keys for storage, I'm looking for a way to get everything.

In context: this will be used in the Chrome extension to sync settings.

+4
source share
2 answers

If you want to do this, you can simply skip each item and add 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 you can use Tokenizer or something like that to break, using spaces as separators. You can add a “Key” + i and / or “value” + i handle to each element to help you parse or search for the element without having to scroll through the keys to find a suitable one.

+3
source

Why do you need this? In addition, localStorage is an object that contains all key pairs: values ​​stored in the browser. If you want to copy it, you must skip its properties.

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

There are several libraries that achieve this with varying levels of complexity and / or functionality. For example, jStorage allows you to use userData in IE if localStorage not available. My Storage.js only wraps localStorage , but has methods for working with multiple items at once.

0
source

All Articles