Junior
How can a JavaScript object be saved in localStorage?
sobes.tech AI
Answer from AI
Using JSON.stringify() to serialize an object into a string before saving and JSON.parse() to deserialize the string back into an object when retrieving.
// Example object
const userSettings = {
theme: 'dark',
fontSize: 16,
notifications: true
};
// Saving the object to localStorage
localStorage.setItem('userSettings', JSON.stringify(userSettings));
// Retrieving the object from localStorage
const storedSettings = localStorage.getItem('userSettings');
// Deserializing the string back into an object
if (storedSettings) {
const parsedSettings = JSON.parse(storedSettings);
console.log(parsedSettings);
// Will output: { theme: 'dark', fontSize: 16, notifications: true }
}