Last active
September 14, 2016 23:34
-
-
Save paulfarino/1db10edcfd578e72618ca71196ed7385 to your computer and use it in GitHub Desktop.
Store a JS object in localstorage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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)); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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