Sometimes, we want to save JavaScript objects in sessionStorage.
In this article, we’ll look at how to save JavaScript objects in sessionStorage.
How to save JavaScript objects in sessionStorage?
To save JavaScript objects in sessionStorage, we convert the object to a string before saving it.
For instance, we write
const user = { name: "jane" };
sessionStorage.setItem("user", JSON.stringify(user));
const obj = JSON.parse(sessionStorage.user);
to call JSON.stringify
with user
to convert user
to a JSON string.
Then we call setItem
to save the string with key 'user'
.
And then we can get the value and parse it back to an object with
JSON.parse(sessionStorage.user)
Conclusion
To save JavaScript objects in sessionStorage, we convert the object to a string before saving it.