How do I get an object's value stored in localStorage?

那年仲夏 提交于 2020-03-16 08:11:09

问题


I have stored an object with multiple properties in localStorage. It does not contain a single value like a string or a number. The name of the localStorage key is UserData and its value is the following object:

{
    key: "1287C31D714BE16FBD44D093E4173CFF"
    logTime: "20191013190439"
    operatorDni: "46653980"    
}

I need to retrieve the value of the object property operatorDni in order to perform some actions in my code. I have tried to retrieve it using this line of code:

operatorDni: string;

this.operatorDni= localStorage.getItem('UserData.operatorDni');

But I get null.

How can I get a property of an object in localStorage with the key? What am I doing wrong?

Thank you very much.


回答1:


Use JSON.parse like

var userData= JSON.parse(localStorage.getItem('UserData'))
this.operatorDni=userData.operatorDni;

Also save it like

localStorage.setItem('UserData',JSON.stringify(yourObject))


来源:https://stackoverflow.com/questions/58371034/how-do-i-get-an-objects-value-stored-in-localstorage

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