简体   繁体   中英

Using localStorage and sessionStorage as tree of elements

During application refactoring I very lately found out about localStorage and sessionStorage are key-value storages, so question: is thee any JavaScript implementation for using localStorage, sessionStorage as JSON, and stay ability to easely edit them via browser debug tools?

Example: We create some value for key application, it have sub-keys like settings, connection, they have subkeys for properties.

So, easy way to interact them like this:

if (localStorage.application.connection.URI.slice(0, 5) === "https") { ... }

And, if we need to destroy branch for properties and re-init them:

localStorage.application.connection = undefined;

Any way to do this? I know, I can use

if (localStorage.getItem("application.connection.URI").slice(0, 5) === "https") { ... }

And (thx to this answer How to remove localStorage data starting with a certain string? )

for (key in localStorage) {
    if (key.substring(0,22) == 'application.connection') {
        localStorage.removeItem(key);
    }
}

But it is slightly hard to read and use.

Any suggestions? And sorry for my english.

A bit late but here you go: I implemented DotStorage as a hacky solution for this about a year ago.

It's neither maintained nor fully tested but it does the job.
...I just checked the repo: be aware that you need pako for this to work....

Don't use it for big things though as this is realized by automatically wrapping objects and their properties in proxies - implementing deep change detection by trapping everything.

Usage: like any other Javascript object, it's just persistent:

dotStorage.Hello = "World";
// reload page
console.assert(dotStorage.Hello == "World");


You can take a look at my JSFiddle based test file here

Example:

var myObj = {"New": "object"};

// save the object
dotStorage.refTest = myObj;

// get proxified instance
myObj = dotStorage.refTest;

// change nested properties
myObj.New = {"nested": {"otherObject": [0, 1]}};
console.log(JSON.stringify(dotStorage.refTest.New));

// reload the page ------------------------------------------

// change more nested properties
myObj.New.nested = 2;

// everything is still there
console.log(JSON.stringify(dotStorage.refTest.New));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM