Monthly Archives: May 2014

Store Objects in JavaScripts HTML5 LocalStorage

LocalStorage is really useful. It can save variables (just like cookies) in a users browser. But there is one problem which many people seem to encounter: Storing objects does not work.

localStorage.setItem('test', { someKey: 123 });

This line of code saves our object as a string. If we restore the stored item, we will get this:

localStorage.getItem('test');
// [object Object]

This is because JavaScript calls the .toString() method on our object, which simply outputs [object Object]. If we want to store and restore objects, we need to encode them into a JSON string. The following code implements my most used solution for storing objects:

var LocalStorageManager = function() { 
    if (typeof localStorage === 'undefined') {
        throw 'localStorage cannot be used in this browser';   
    }
};

LocalStorageManager.prototype.setObject = function(key, obj) {
    localStorage.setItem(key, JSON.stringify(obj));
};

LocalStorageManager.prototype.getObject = function(key) {
    return JSON.parse(localStorage.getItem(key));
};
var storage = new LocalStorageManager();
storage.setObject('user', { name: 'john', age: 26 });
console.log(storage.getObject('user'));

Yes, you could do this without an additional object, but it keeps stuff cleaner if you use one. If you got any questions, feel free to contact me in the comment section down below.