Junior
How can you save a JavaScript object in localStorage?
sobes.tech AI
Answer from AI
// Create an object
const myObject = {
name: "John",
age: 30,
city: "New York"
};
// Serialize the object into a JSON string
const jsonString = JSON.stringify(myObject);
// Save the string in localStorage with the key "userData"
localStorage.setItem("userData", jsonString);
// Example of retrieving and deserializing the object from localStorage
// const storedString = localStorage.getItem("userData");
// const storedObject = JSON.parse(storedString);
// console.log(storedObject); // Will output: { name: "John", age: 30, city: "New York" }