i am not able to load array from session storage in java script

299 Views Asked by At

I am not able to restore a created array in html and reuse it again. I have used Json but do not work with me. in the below code. I'm trying to reload items which is an array created in another page. when i try to load it, it did not work. how can i fix this? does json need header file? Thank you.

$( document ).ready(function() {
    var count=sessionStorage.getItem('items');      
)};
2

There are 2 best solutions below

0
On BEST ANSWER

The sessionStorageproperty allows you to access a session Storage object for the current origin.It is two way process first of all stringifyobject before storing to session and second parseto getting back .

     var user = {'name':'John'};
     sessionStorage['user'] = JSON.stringify(user);
     console.log(sessionStorage['user']);
     var obj = JSON.parse(sessionStorage['user']);
     console.log(Object.keys(obj).length);

Here is fiddle.Opening a page in a new tab or window will cause a new session to be initiated. More About session storage.

0
On

You have to convert your array to a string before setting and back again when your get the item

var letters = ['a', 'b', 'c'];
sessionStorage.setItem("letters", JSON.stringify(letters));
var storedLetters = JSON.parse(sessionStorage.getItem("letters"));

console.log(storedLetters);