How to Store Objects in HTML5 localStorage with JavaScript?

Spread the love

Sometimes, we want to Store Objects in HTML5 localStorage in our JavaScript app.

In this article, we’ll look at how to store objects in HTML5 localStorage with JavaScript.

How to Store Objects in HTML5 localStorage with JavaScript?

To store objects in HTML5 localStorage with JavaScript, we can use JSON.stringify to convert the JavaScript object into a string.

Then we use the localStorage.setItem method to save the stringified JSON object into local storage.

For instance, we write

const testObject = {
  'one': 1,
  'two': 2,
  'three': 3
};

localStorage.setItem('testObject', JSON.stringify(testObject));

const retrievedObject = localStorage.getItem('testObject');

console.log(jSON.parse(retrievedObject));

to call JSON.stringify with testObject to return the string version of testObject.

Then we call setItem with the key of the local storage entry and the value set to the stringifyed JSON object.

We have to convert testObject to a string before storing it with setItem since local storage only store strings.

When we want to retrieve the item, we call localStorage.getItem with the 'testObject' key.

And then we call JSON.parse with the retrievedObject string to convert the string back to JavaScript object.

Conclusion

To store objects in HTML5 localStorage with JavaScript, we can use JSON.stringify to convert the JavaScript object into a string.

Then we use the localStorage.setItem method to save the stringified JSON object into local storage.

Leave a Reply

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