javascript - How to store and update a localStorage key object which has properties of different data types? -
this first time using localstorage
, store localstorage
key object has properties of different data types ,for example key "localstor
" ,it object containing 2 properties :
localstor= { usermsg : string , userinfo : (object) { id: string , username: string , pwd :string } }
the property usermsg
of type string
while property userinfo
of type object
.
i know how set , item containing objects based on this question , in case don't know how set , kind of key? , espacially if want update object userinfo in localstor how that?
any appreciated.
i don't know if understood question, , if did, please tell me can correct answer, think trying manipulate item kept in cache localstorage
, , data, instance, object contains data of multiple types.
lets have object localstor
(i added tabs it's easier see , debug);
var localstor = { usermsg : "message", userinfo :{ id: "someid", username: "someusername", pwd : "somepassword" } }
putting localstorage super easy (as pointed out know how do) need choose key. here, chose "obj" key:
localstorage.setitem("obj", json.stringify(localstor));
as might have noticed, used function json.stringify()
. did because since have object objects inside, need convert string store it. javascript has function built-in don't need install anything.
how retrieve , update localstor object now?
very easy. retrieve object localstorage.getitem() function, passing "obj" have setted before, , result need convert object type (since stored string before, remember?) using json.parse()
function. after that, can edit properties of object other object:
localstor = json.parse(localstorage.getitem("obj")); localstor.userinfo.username = "anotherusername";
i can set new object localstorage:
localstorage.setitem("obj", json.stringify(localstor));
and that's it! when retrieve again, new value username there.
full code here:
var localstor = { usermsg : "message", userinfo :{ id: "someid", username: "someusername", pwd : "somepassword" } } //put localstor object cache localstorage.setitem("obj", json.stringify(localstor)); //retrieve object localstor = json.parse(localstorage.getitem("obj")); //change username property localstor.userinfo.username = "anotherusername"; //and put editted object cache localstorage.setitem("obj", json.stringify(localstor));
if have doubts yet, please tell me can answer in better way!
Comments
Post a Comment