DEV Community

Ertan Özdemir
Ertan Özdemir

Posted on

6 2

How to add an object to localStorage?

In this note I will show you how to insert an object to localStorage

In some situations you may want to store data in local storage or session storage as an object. So how can you achieve this?

Assume that we have an object and this object stores some tokens.



const tokens = {
token: "meowmeow",
anotherToken: "woofwoof"
}


Enter fullscreen mode Exit fullscreen mode

Writing to localStorage

To set a localStorage item we have to use localStorage.setItem( ) method. This method takes two parameters, key and value. key is the name of our local storage item and the value is basically its value.

We cannot directly store objects in localStorage or session storage. Therefore we have to convert them into JSON string. To do that we have very handy method called JSON.stringify(value). value parameter is going to be object that we want to convert into JSON string. In this example value is tokens



JSON.stringify(tokens)


Enter fullscreen mode Exit fullscreen mode

We learned how to convert object into JSON string. Now, let's add this JSON string to our localStorage



const tokens = {
token: "meowmeow",
anotherToken: "woofwoof"
}

localStorage.setItem("tokens", JSON.stringify(tokens))



Enter fullscreen mode Exit fullscreen mode

If you check your local storage, you can see that your object has been successfully added.

Image description


Reading from localStorage

To read an object from localStorage, we have another handy method called JSON.parse( ). This method helps us to convert JSON string into JavaScript object. But first, we have to get the object from local storage.



const localStorageItem = localStorage.getItem("tokens")
const tokenObject  = JSON.parse(localStorageItem)


console.log(tokenObject)

/*
{
token: "meowmeow",
anotherToken: "woofwoof"
}
*/



Enter fullscreen mode Exit fullscreen mode

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!