Anjan Dutta

How to store and retrieve object in locals torage JavaScript

How to store and retrieve object in locals torage JavaScript

Published On: 31/10/2021

In javascript, an object can not be stored in local storage as it is.

We need to format the object into a string before storing it.

Storing an object in local storage

Because, the local storage setItem function takes the key and value as string parameters.

So, the object must be converted into a string first.

See the below code for reference.

const userObject ={name: "John Doe", phone: "+1-233-223"};
localStorage.setItem('savedUser', JSON.stringify(userObject));

In above example, the JSON.stringify(userObject) converts the object into string before saving it.

Getting an object stored into local storage

To retrieve an object from the local storage, we have to use the getItem function and pass the key name as parameter.

See the reference below.

const sampleObject = localStorage.getItem('userObject');
console.log(JSON.parse(sampleObject));

In the above example, the sampleObject variable receives the stored string value.

Then, to convert the string to an object, we are passing the string into the JSON.parse function.