How to store objects in HTML5 localStorage/sessionStorage

HTML5 localStorage and sessionStorage are powerful web storage features that allow web developers to store data on the client's browser. However, when it comes to storing JavaScript objects in localStorage or sessionStorage, there's an issue. By default, these storage mechanisms only support string values, so when you try to store an object, it gets converted to a string.

In this article, we will explore different approaches to overcome this limitation and successfully store JavaScript objects in HTML5 localStorage/sessionStorage.

Understanding the Issue

Before we dive into the solutions, let's understand why this problem occurs. When you call the localStorage.setItem() or sessionStorage.setItem() methods, the input value is automatically converted to a string. This means that if you pass an object as the value, it will be converted to the string representation of the object, which is [object Object].

Let's take a look at the example code provided in the problem description:

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]);
}

// Put the object into storage
localStorage.setItem('testObject', testObject);

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');

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

Running the above code will result in the following output:

typeof testObject: object
testObject properties:
  one: 1
  two: 2
  three: 3
typeof retrievedObject: string
Value of retrievedObject: [object Object]

As you can see, despite storing the object in localStorage, the retrieved value is a string representation of the object, not the original object itself.

Solutions

1. JSON.stringify() and JSON.parse()

One way to store JavaScript objects in localStorage is to convert the object to a JSON string using the JSON.stringify() method before storing it. Then, when retrieving the value, you can parse the JSON string back to the original object using the JSON.parse() method.

Here's an example that demonstrates this approach:

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

// Convert the object to a JSON string
var jsonString = JSON.stringify(testObject);

// Store the JSON string in localStorage
localStorage.setItem('testObject', jsonString);

// Retrieve the JSON string from localStorage
var retrievedString = localStorage.getItem('testObject');

// Parse the JSON string back to the original object
var retrievedObject = JSON.parse(retrievedString);

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

Running the updated code will now correctly output:

typeof retrievedObject: object
Value of retrievedObject: [object Object]

The object is successfully stored and retrieved from localStorage, maintaining its original structure and properties.

2. Custom Serialization and Deserialization

Another approach to storing JavaScript objects in localStorage is to define custom serialization and deserialization methods. These methods will allow you to convert the object to a string representation for storage and back to its original form when retrieved.

Here's an example implementation of custom serialization and deserialization methods:

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

// Serialize the object
var serializedObject = serializeObject(testObject);

// Store the serialized object in localStorage
localStorage.setItem('testObject', serializedObject);

// Retrieve the serialized object from localStorage
var retrievedObject = localStorage.getItem('testObject');

// Deserialize the object
var deserializedObject = deserializeObject(retrievedObject);

console.log('typeof deserializedObject: ' + typeof deserializedObject);
console.log('Value of deserializedObject: ' + deserializedObject);

// Custom serialization method
function serializeObject(obj) {
    var serialized = '';
    for (var prop in obj) {
        serialized += prop + ':' + obj[prop] + ';';
    }
    return serialized;
}

// Custom deserialization method
function deserializeObject(serialized) {
    var obj = {};
    var properties = serialized.split(';');
    for (var i = 0; i < properties.length - 1; i++) {
        var keyValue = properties[i].split(':');
        var key = keyValue[0];
        var value = parseInt(keyValue[1]);
        obj[key] = value;
    }
    return obj;
}

Running the updated code will output:

typeof deserializedObject: object
Value of deserializedObject: [object Object]

With this approach, you have full control over how the object is serialized and deserialized. You can customize the serialization and deserialization methods according to your specific requirements.

Conclusion

Storing JavaScript objects in HTML5 localStorage or sessionStorage can be achieved by either using JSON.stringify() and JSON.parse() methods or implementing custom serialization and deserialization methods. Both approaches allow you to successfully store and retrieve objects, preserving their original structure and properties.

It's important to note that localStorage and sessionStorage have storage limitations, typically around 5MB per domain. Exceeding these limits can lead to storage errors or clearing of older data.

Consider the nature and size of the objects you are storing, and implement appropriate error handling and data management strategies to ensure a smooth user experience.