Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting an array of objects to sessionStorage

Ok, so I have this JSON:

{"Status":"OK!","ListaPermessi":
[{"IdPermesso":10,"Nome":"WIND_PARAMS"},
 {"IdPermesso":11,"Nome":"ADMIN_SERVER"},
 {"IdPermesso":21,"Nome":"REC"},
 {"IdPermesso":22,"Nome":"REC_DIST"},
 {"IdPermesso":23,"Nome":"REC_DIST_CR"}
]}

My code is:

var parsedResult = JSON.parse(result); // where result is the above JSON
if (parsedResult.Status === "OK!") {
    // Set sessionStorage vars
    if (typeof(Storage) !== "undefined") {
        // localStorage & sessionStorage support!

        sessionStorage.setItem("ListaPermessi", parsedResult.ListaPermessi);
    }
    else {
        // Sorry! No web storage support :(
    }
}

But... this is not working properly! After the assignment, the sessionStorage seen from Firebug looks like this:

sessionStorage:

  • ListaPermessi = "[object Object],[object Object],[object Object],[object Object],[object Object]"

What is the proper way to assign an array of objects to a sessionStorage variable from javascript?

like image 893
Teslo. Avatar asked Sep 24 '12 10:09

Teslo.


People also ask

How do you set an array of objects in session storage?

My code is: var parsedResult = JSON. parse(result); // where result is the above JSON if (parsedResult. Status === "OK!") { // Set sessionStorage vars if (typeof(Storage) !==

Can you store an array in sessionStorage?

Saving arrays to localStorage and sessionStorageWe can now save it to localStorage or sessionStorage using the setItem() method: localStorage. setItem("ourarraykey",JSON. stringify(ourArray));

Can we store object in sessionStorage?

The sessionStorage object stores data for only one session. (The data is deleted when the browser is closed).


1 Answers

You need to turn it back into a JSON string. You can do that with the JSON.stringify method:

sessionStorage.setItem("ListaPermessi", JSON.stringify(parsedResult.ListaPermessi));

The reason for this is that web storage can only store strings, and the default toString method of Object returns, as you've now seen, "[object Object]".


Side note: typeof is an operator, not a function, so there's no need for the parentheses:

if (typeof Storage !== "undefined") { //...
like image 69
James Allardice Avatar answered Oct 22 '22 16:10

James Allardice