I need to store an object like the one I the example below in localstorage
. I need to be able to retrieve this object and edit it, then save it back into localStorage
for next time.
var data = {lastEdit:"September", expires:"December", records:[{arrives: "12:45", departs: "12:51"}, {arrives: "13:03", departs: "13:04"}]};
I tried this but it said 'undefined':
localStorage.setItem("dataStore1", data);
var output = localStorage.getItem("dataStore1");
What can I do to fix it?
From Using the Web Storage API:
"Storage objects are simple key-value stores, similar to objects, but they stay intact through page loads. The keys and the values are always strings (note that integer keys will be automatically converted to strings, just like what objects do)."
You cannot store a complex Object
value in localStorage. Sorry.
Instead, you should serialize your Object as a string [hint: JSON.stringify()
] and then after retrieving it parse from JSON string back to Object [hint: JSON.parse()
].
Use JSON.stringify()
to set JSON
and JSON.parse()
to convert JSON
to a JavaScript object; localStorage
expects a string to be set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With