I'd like to store a JavaScript object in HTML5 localStorage, but my object is apparently being converted to a string.
Solution 1:
Looking at the Apple , Mozilla and Microsoft documentation, the functionality seems to be limited to handle only string key/value pairs.
A workaround can be to stringify our object before storing it, and later parse it when we retrieve it:
Solution 2:
A little improve to Justin's variant:
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).
UPD. Added variable that Mark Storer mentioned in comment
Solution 3:
We might find it useful to extend the Storage object with these handy methods:
This way we get the functionality that we really wanted even though underneath the APWE only supports strings.
Solution 4:
Extending the Storage object is an awesome solution. For my API, WE have created a facade for localStorage and then check if it is an object or not while setting and getting.
Solution 5:
There is a great library that wraps many solutions so it even supports older browsers called jStorage
We can set an object