If possible, I would like to be able to use shorthand notation to get an item from localStorage
and then use JSON.parse()
on it.
In my code below, if I use the following it works:
var retrievedObject = JSON.parse(localStorage.getItem('testObject')); //works
However, if I use one of the two following shorthand options, it doesn't work:
var retrievedObject = JSON.parse(localStorage.testObject); //doesn't work
var retrievedObject = JSON.parse(localStorage['testObject']); //doesn't work
All of my code is below and on jsFiddle: http://jsfiddle.net/TestB/1/.
//var retrievedObject = JSON.parse(localStorage.getItem('testObject')); //works
var retrievedObject = JSON.parse(localStorage.testObject); //doesn't work
//var retrievedObject = JSON.parse(localStorage['testObject']); //doesn't work
if (retrievedObject == null) {
var testObject = { 'one': 1, 'two': 2, 'three': 3 };
// Put the object into storage
localStorage.testObject = JSON.stringify(testObject);
}
else {
retrievedObject.four = 4;
// Put the object into storage
localStorage.testObject = JSON.stringify(retrievedObject);
}
// Retrieve the object from storage
var retrievedObject = JSON.parse(localStorage.getItem('testObject'));
console.log('retrievedObject: ', retrievedObject);