Вопрос

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?

Это было полезно?

Решение

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'])

Другие советы

From developer.mozilla.com:

The DOM Storage mechanism is a means through which string key/value pairs can be securely stored and later retrieved for use.

Hence I think you cannot store array/dictionary directly in session storage. I highly suggest you that check this link out: https://developer.mozilla.org/en-US/docs/DOM/Storage

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top