How to store and retrieve JavaScript objects in HTML5 localStorage

Last Updated on :February 25, 2024

window.localStorage allows storing data on a client-side browser that persists even after the browser window is closed.

Data stored in localStorage can be accessed throughout a particular domain. For instance, data stored in the localStorage object from devtechinfo can be accessed by any page on same domain.

LocalStorage can only store strings, which presents a challenge when dealing with complex JavaScript objects. However, by leveraging the JSON.stringify() and JSON.parse() methods, developers can easily store and retrieve JavaScript objects in HTML5 localStorage. In this article, we will explore how to accomplish this effectively.

Storing Objects in localStorage:

To store JavaScript objects in localStorage, we need to convert them into strings. The JSON.stringify() method comes in handy for this purpose. Here is an example


var empObject =
{
"emp_name": "John",
"emp_dept": "IT",
"emp_age": 32,
"emp_salary": 5400
}
// Put the object into storage
localStorage.setItem('empObject', JSON.stringify(empObject));

Retrieving Objects from localStorage:

After storing the object in localStorage, we can retrieve it and convert it back into a JavaScript object. The JSON.parse() method allows us to accomplish this. Let’s see an example:


// Retrieve the object string from localStorage
var storedEmpObjectString = localStorage.getItem("empObject");

// Convert the string back to an object
var storedObject = JSON.parse(storedEmpObjectString);
console.log('storedObject: ', storedObject);
console.log('emp_name: ', storedObject.emp_name);
console.log('emp_dept: ', storedObject.emp_dept);

Removing Objects from localStorage:

To remove an item from localStorage, we can use the removeItem() method. In the below code snippet, we remove the item with the key “empObject” from localStorage using the removeItem() method.


window.localStorage.removeItem("empObject");

Conclusion:

HTML5 localStorage provides a convenient way to store data on the client-side, but it can only store strings. By utilizing the JSON.stringify() and JSON.parse() methods, we can effectively store and retrieve JavaScript objects in localStorage. The stringify() method converts the object into a string, while the parse() method converts the string back into an object.

You may also like...

Leave a Reply

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