I don't know if I understood your question, and if I did, please tell me so I can correct my answer, but I think what you are trying to do is manipulate an item you kept in cache with localStorage
, and this data, for instance, is an object that contains data of multiple types.
So lets say you have your object localstor
(I added some tabs so it's easier to see and debug);
var localstor = {
userMsg : "Message",
userInfo :{
ID: "SomeID",
username: "SomeUsername",
pwd : "SomePassword"
}
}
Putting it into localStorage is super easy (as you pointed out you already know how to do) so you only need to choose a key. Here, I chose "obj" as key:
localStorage.setItem("obj", JSON.stringify(localstor));
As you might have noticed, I used a function JSON.stringify()
.
I did it because since you have an object with objects inside, you need to convert it into a String to store it. JavaScript has this function already built-in so you don't need to install anything.
How do I retrieve and update the localstor object now?
Very easy.
I retrieve the object with the localStorage.getItem() function, passing the "obj" I have setted before, and this result I need to convert it back to the Object type (since we stored it as a String before, remember?) using the JSON.parse()
function. After that, I can edit the properties of the object as I would do with any other object:
localstor = JSON.parse(localStorage.getItem("obj"));
localstor.userInfo.username = "AnotherUsername";
I can set the new object back to the LocalStorage:
localStorage.setItem("obj", JSON.stringify(localstor));
And that's it! now when I retrieve it again, the new value for username will be there.
Full code here:
var localstor = {
userMsg : "Message",
userInfo :{
ID: "SomeID",
username: "SomeUsername",
pwd : "SomePassword"
}
}
//Put the localstor object into the cache
localStorage.setItem("obj", JSON.stringify(localstor));
//Retrieve the object
localstor = JSON.parse(localStorage.getItem("obj"));
//Change the username property
localstor.userInfo.username = "AnotherUsername";
//And put the editted object back to cache
localStorage.setItem("obj", JSON.stringify(localstor));
If you have any doubts yet, please tell me so I can answer in a better way!