Sobes.tech
Junior

How can a JavaScript object be saved in localStorage?

sobes.tech AI

Answer from AI

To save an object in localStorage, it needs to be converted into a string, usually using JSON.stringify(). When retrieving from localStorage, the string representation of the object is converted back into an object using JSON.parse().

Here's an example:

Saving an object:

// Original object
const myObject = {
  name: 'Example',
  value: 42
};

// Convert object to JSON string and save in localStorage
localStorage.setItem('myStoredObject', JSON.stringify(myObject));

Reading the object:

// Get the string from localStorage
const storedObjectString = localStorage.getItem('myStoredObject');

// Convert JSON string back to object (if it exists)
if (storedObjectString) {
  const myReadObject = JSON.parse(storedObjectString);
  // Now myReadObject is a JavaScript object again
  console.log(myReadObject.name); // Outputs: Example
}

It's important to remember that localStorage stores data only as strings. Therefore, directly saving an object will result in it being stored as the string [object Object], which is useless.

Also, consider the size limitations of localStorage (usually around 5 MB) and that it is not intended for storing confidential data, as it is accessible from any script on the same domain.