Skip to content

Instantly share code, notes, and snippets.

@paulfarino
Last active September 14, 2016 23:34
Show Gist options
  • Save paulfarino/1db10edcfd578e72618ca71196ed7385 to your computer and use it in GitHub Desktop.
Save paulfarino/1db10edcfd578e72618ca71196ed7385 to your computer and use it in GitHub Desktop.
Store a JS object in localstorage
// Local Storage workaround: Stringify your object before storing it, and later parse it when you retrieve it
// Create object
var testObject = { 'one': 1, 'two': 2, 'three': 3 };
// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
console.log('retrievedObject: ', JSON.parse(retrievedObject));
// Because of short-circuit evaluation, getObject() will immediately return null if key is not in Storage. It also will not throw a SyntaxError exception if value is "" (the empty string; JSON.parse() cannot handle that).
Storage.prototype.setObject = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObject = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment