sessionStorage not storing original object

2019-03-02 05:12发布

I have an object which I'm getting by executing a function of SDK. When I try to store the object in session storage and the retrieve the object, the retrieved object looks same as original but when I perform operations on the new object I'm getting error.

var xyzObject = some_function();

sessionStorage.setItem("xyzObject",xyzObject);

var obj = JSON.parse(sessionStorage.getItem("xyzObject"));

obj.some_other_function();

It is showing an error as obj.some_other_function is not a function. Whereas xyzObject.some_other_function works perfectly.

2条回答
老娘就宠你
2楼-- · 2019-03-02 05:28

You cannot store an object in the sessionStorage or localStorage. The only possible method is to stringify the object and save that in sessionStorage and on receiving the object from sessionStorage you just parse the object to JSON.

var xyzObject = some_function();

sessionStorage.setItem("xyzObject",JSON.stringify(xyzObject));

var stringData = sessionStorage.getItem("xyzObject");

var obj = JSON.parse(stringData);

obj.some_other_function();
查看更多
Luminary・发光体
3楼-- · 2019-03-02 05:35

Try

sessionStorage.setItem('xyzObject', JSON.stringify(xyzObject);

And retrieve using:

  JSON.parse(sessionStorage.getItem('xyzObject'));
查看更多
登录 后发表回答