Search code examples
javascripthtmlsession-variablessession-storage

Is there something similar to sessionStorage but with multidimensional keys?


I'd like to save off values of a tree-like structure locally, then retrieve them based on user interaction. After some research, I found that sessionStorage (or localStorage) might be a good way to go about doing this. But I'm having trouble saving nested data.

Normally you have:

sessionStorage['key'] = 'someString';

I tried to implement something like:

sessionStorage['key1'] = [];
sessionStorage['key1']['key2'] = 'someString';

but I got an undefined error.

I've checked out few other storage libraries, but they only offer that single key-value pair option. Is there anything I'm missing?


Solution

  • Use JSON to serialise the nested data into a string, then decode it when you need to access it as an object...

    var nested = {some:{nested:'object'}}
    var asJson = JSON.stringify(nested)
    sessionStorage['data'] = asJson
    var asObject = JSON.parse(sessionStorage['data'])