Lesson 56 - Storing Complex Data in localStorage
So far, we've learned how to store and retrieve simple key-value pairs using localStorage
. However, JavaScript objects and arrays cannot be stored directly in localStorage
because it only supports string values. In this lesson, we'll explore how to store complex data types like objects and arrays using JSON.
Storing Objects in localStorage
To store an object in localStorage
, we need to convert it into a string using JSON.stringify()
before saving it.
Example:
const user = {
name: "Alice",
age: 25,
city: "New York"
};
// Convert object to string and store in localStorage
localStorage.setItem("user", JSON.stringify(user));
console.log("User stored in localStorage");
Retrieving Objects from localStorage
Since we stored the object as a string, we need to parse it back into an object using JSON.parse()
when retrieving it.
Example:
const storedUser = localStorage.getItem("user");
if (storedUser) {
const userObject = JSON.parse(storedUser);
console.log("Retrieved User:", userObject);
}
Storing Arrays in localStorage
We can store arrays in the same way using JSON.stringify()
.
Example:
const favoriteColors = ["Red", "Blue", "Green"];
// Convert array to string and store in localStorage
localStorage.setItem("colors", JSON.stringify(favoriteColors));
console.log("Colors stored in localStorage");
Retrieving Arrays from localStorage
We use JSON.parse()
to retrieve and convert the stored string back to an array.
Example:
const storedColors = localStorage.getItem("colors");
if (storedColors) {
const colorsArray = JSON.parse(storedColors);
console.log("Retrieved Colors:", colorsArray);
}
Try Your Hand
- Create an array of objects representing users (name, age, and email) and store it in
localStorage
. - Retrieve the stored array from
localStorage
and log each user's name and email. - Modify one of the user objects, update
localStorage
, and retrieve it again.
Summary
localStorage
only supports string values.- Use
JSON.stringify()
to store objects and arrays as strings. - Use
JSON.parse()
to retrieve and convert them back to their original form.
Now you can efficiently store and retrieve complex data in localStorage
!