Categories
JavaScript Answers

How to save JavaScript objects in sessionStorage?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *