PASSWORD RESET

Your destination for complete Tech news

How to store objects in localStorage and sessionStorage?

364 0
< 1 min read

To store objects in localStorage or sessionStorage in JavaScript, you need to serialize the object into a string representation that can be stored in the storage. You can use the JSON.stringify method to serialize the object into a JSON string, and then use the setItem method of the localStorage or sessionStorage object to store the string.

Here is an example of how to store an object in localStorage:

let obj = {
  name: 'John',
  age: 30
};

let objString = JSON.stringify(obj);
localStorage.setItem('myObject', objString);

To retrieve the object from localStorage, you can use the getItem method to retrieve the string representation of the object, and then use the JSON.parse method to parse the string back into an object.

let objString = localStorage.getItem('myObject');
let obj = JSON.parse(objString);

console.log(obj.name);  // 'John'
console.log(obj.age);   // 30

The process for storing and retrieving objects in sessionStorage is the same as for localStorage, except you would use the sessionStorage object instead of the localStorage object.

Note that localStorage and sessionStorage can only store strings, so you need to serialize and parse objects when storing and retrieving them. The localStorage and sessionStorage objects are also limited in size, and they are not accessible from other domains, so they are not suitable for storing large amounts of data or data that needs to be shared between different domains.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.