I'm trying to save some data in localstorage. My script looks like this:
localStorage.clear(); //only for testing
if(typeof localStorage.akten == "undefined") {
localStorage.akten = new Array();
}
var nam = "alpha";
localStorage.akten[nam] = {
"beta": 12
};
localStorage["a_akte"] = nam;
But if I do console.log(localStorage);
or console.log(localStorage.akten);
akten
is only an empty string? Why? With an normal object instead of localStorage it works well.
I'm trying to save some data in localstorage. My script looks like this:
localStorage.clear(); //only for testing
if(typeof localStorage.akten == "undefined") {
localStorage.akten = new Array();
}
var nam = "alpha";
localStorage.akten[nam] = {
"beta": 12
};
localStorage["a_akte"] = nam;
But if I do console.log(localStorage);
or console.log(localStorage.akten);
akten
is only an empty string? Why? With an normal object instead of localStorage it works well.
-
JavaScript
Array
accepts only numerical indices. When you convert your array to JSON, the serialization will not include your arbitrary named properties (e.g.alpha
). You should use anObject
instead. And you can use literals (e.g.{}
forObject
and[]
forArray
). – eyelidlessness Commented Sep 5, 2013 at 14:13
2 Answers
Reset to default 5Suprisingly the devil is in the details. localStorage
only stores strings. Encode your objects as JSON before depositing them there using for example JSON.stringify()
and JSON.parse()
.
This is because localStorage
is not an Object; it's an interface. You can only assign a String to it, and the best way to do so is with localStorage.setItem
. If you want to be setting more plex data, you'll need to encode it as JSON first.
function localStore(key, obj) {
return window.localStorage.setItem(key, JSON.stringify(obj));
}
function localGet(key) {
return JSON.parse(window.localStorage.getItem(key));
}
localStore('foo', {bar: 'baz'});
localGet('foo'); // Object {bar: "baz"}