sessionStorage not storing original object

回眸只為那壹抹淺笑 提交于 2019-12-04 05:17:22

问题


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.


回答1:


Try

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

And retrieve using:

  JSON.parse(sessionStorage.getItem('xyzObject'));



回答2:


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();


来源:https://stackoverflow.com/questions/40461988/sessionstorage-not-storing-original-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!