helencousins.com

Mastering Object Storage in JavaScript's localStorage

Written on

Understanding the Challenge

Have you ever tried to save a JavaScript object in HTML5 localStorage, only to find it converting into a string? You're certainly not alone! This is a common challenge faced by many developers when dealing with localStorage, and it can be quite confusing initially.

The Dilemma

Let's illustrate this issue with a sample code snippet:

var testObject = { 'one': 1, 'two': 2, 'three': 3 };

console.log('typeof testObject: ' + typeof testObject);

console.log('testObject properties:');

for (var prop in testObject) {

console.log(' ' + prop + ': ' + testObject[prop]);

}

// Store the object in localStorage

localStorage.setItem('testObject', testObject);

// Retrieve the object from localStorage

var retrievedObject = localStorage.getItem('testObject');

console.log('typeof retrievedObject: ' + typeof retrievedObject);

console.log('Value of retrievedObject: ' + retrievedObject);

When you execute this code, the output will be as follows:

typeof testObject: object

testObject properties:

one: 1

two: 2

three: 3

typeof retrievedObject: string

Value of retrievedObject: [object Object]

As demonstrated, while testObject is indeed an object, retrieving it from localStorage results in a string representation: "[object Object]".

The Underlying Cause

This behavior stems from the way localStorage operates. According to the HTML5 Web Storage specification, the setItem method of the Storage object (which localStorage is an instance of) can only handle string key/value pairs. Therefore, when a non-string value is passed to setItem, it gets converted to a string using the toString() method. For objects, the default implementation of toString() yields the string "[object Object]", which is why we see that output upon retrieval.

The Solution

To successfully store and retrieve JavaScript objects in localStorage, we need to serialize and deserialize them using JSON (JavaScript Object Notation). JSON effectively represents JavaScript objects as strings, making it ideal for storage in localStorage.

Here's how we can modify our code to incorporate JSON:

var testObject = { 'one': 1, 'two': 2, 'three': 3 };

// Store the object in localStorage

localStorage.setItem('testObject', JSON.stringify(testObject));

// Retrieve the object from localStorage

var retrievedObject = JSON.parse(localStorage.getItem('testObject'));

console.log('retrievedObject: ', retrievedObject);

In this revised version, we use JSON.stringify(testObject) to convert testObject into a JSON string before storing it. When retrieving the value, we apply JSON.parse(localStorage.getItem('testObject')) to transform the JSON string back into a JavaScript object.

Executing this code will yield:

retrievedObject: { one: 1, two: 2, three: 3 }

Success! We have now effectively stored and retrieved a JavaScript object in localStorage.

Further Examples

Let’s delve into a couple of additional examples to reinforce our understanding of storing objects in localStorage.

Example 1: Storing an Array of Objects

Consider we have an array of objects that represent a collection of books, and we want to store this array in localStorage to ensure it persists across page reloads or browser sessions:

var books = [

{ title: 'The Great Gatsby', author: 'F. Scott Fitzgerald', year: 1925 },

{ title: 'To Kill a Mockingbird', author: 'Harper Lee', year: 1960 },

{ title: '1984', author: 'George Orwell', year: 1949 }

];

// Store the array in localStorage

localStorage.setItem('books', JSON.stringify(books));

// Retrieve the array from localStorage

var storedBooks = JSON.parse(localStorage.getItem('books'));

console.log('Stored Books:', storedBooks);

In this scenario, we begin by defining an array of book objects. Using JSON.stringify(books), we convert the array into a JSON string and store it in localStorage under the key 'books'. To retrieve the array, we apply JSON.parse(localStorage.getItem('books')) to convert the JSON string back into an array of objects.

Example 2: Storing User Preferences

Another typical application of localStorage is to save user preferences or settings within a web application. For instance, let’s say we have a simple drawing application where users can customize the brush color and size:

var userPreferences = {

brushColor: '#000000',

brushSize: 5

};

// Store user preferences in localStorage

localStorage.setItem('userPreferences', JSON.stringify(userPreferences));

// Retrieve user preferences from localStorage

var storedPreferences = JSON.parse(localStorage.getItem('userPreferences'));

console.log('User Preferences:', storedPreferences);

In this example, we define an object named userPreferences that captures the user's brush color and size selections. We then use JSON.stringify(userPreferences) to convert the object into a JSON string, which we store in localStorage under the key 'userPreferences'. To retrieve the preferences, we utilize JSON.parse(localStorage.getItem('userPreferences')) to revert the JSON string back into a JavaScript object.

By saving user preferences in localStorage, we ensure that their settings remain intact across page reloads or browser sessions, thereby enhancing the user experience.

Conclusion

In summary, we have learned that localStorage is limited to storing string key/value pairs, and that objects must be serialized and deserialized using JSON for proper storage and retrieval. This can all be accomplished using JSON.stringify and JSON.parse.

Additional Resources

This video titled "Storing Objects with Local Storage in JavaScript" delves into the fundamentals of managing localStorage effectively.

Another informative video, "How to Store Objects and Arrays in Local Storage," expands on practical techniques for storing various data types using localStorage.

Thank you for engaging with the In Plain English community!

Be sure to connect with us on X | LinkedIn | YouTube | Discord | Newsletter and explore more content at Stackademic | CoFeed | Venture | Cubed.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Unlocking the Power of Node.js: Your Guide to Building APIs

Discover how to harness Node.js for creating powerful RESTful APIs with this comprehensive guide packed with tips and resources.

# Don’t Let Your Smartphone Dominate Your Life: A Personal Take

A reflection on the importance of maintaining control over technology and cherishing real connections.

# Explore Twos: The Ultimate To-Do List Application

Discover how Twos serves as a multifunctional tool for managing tasks, notes, and reminders effectively.