How to set and fetch saved objects in session in JavaScript

4

I'm wondering how do I save an Array of objects in the session, and then how to retrieve them. Today I use sessionStorage.setItem("pessoa", arrayPessoa); and sessionStorage.getItem("pessoa"); , but it is giving null when I send it to the console.

How to solve this?

    
asked by anonymous 27.10.2015 / 18:38

2 answers

4

SessionStorage does not directly accept an object because it is created by key / value, a way to insert and then read an object is to transform it into string with the function JSON.stringify (), then you can get the session using the sessionStorage.getItem () and give a parse in the value, example of how it could be implemented:

Example:

 var b = {'nome': 'Gabriel', 'sobrenome': 'Rodrigues'};
 b = JSON.stringify(b);
 sessionStorage.setItem('chave', b);
 var c = JSON.parse(sessionStorage.getItem('chave'));
 console.info(c);

See working at Jsfiddle

    
27.10.2015 / 19:08
1

If you can create a JSON for the Person array:

{"Status":"OK!","Pessoa":
[{"IdPessoa":01,"Nome":"JOAO"},
 {"IdPessoa":02,"Nome":"MARIA"}
]}

Then pass the JSON in the form of a String:

var parsedResult = JSON.parse(result);
sessionStorage.setItem("Pessoa", JSON.stringify(parsedResult.Pessoa));

In this case JSON.parse(result) , result is a dynamic JSON.

    
27.10.2015 / 19:08