How do I store an array in localStorage?
The localStorage
and sessionStorage
can only handle strings. You can extend the default storage-objects to handle arrays and objects. Just include this script and use the new methods:
Storage.prototype.setObj = function(key, obj) {
return this.setItem(key, JSON.stringify(obj))
}
Storage.prototype.getObj = function(key) {
return JSON.parse(this.getItem(key))
}
Use localStorage.setObj(key, value)
to save an array or object and localStorage.getObj(key)
to retrieve it. The same methods work with the sessionStorage
object.
If you just use the new methods to access the storage, every value will be converted to a JSON-string before saving and parsed before it is returned by the getter.
localStorage
only supports strings. Use JSON.stringify()
and JSON.parse()
.
var names = [];
names[0] = prompt("New member name?");
localStorage.setItem("names", JSON.stringify(names));
//...
var storedNames = JSON.parse(localStorage.getItem("names"));
You can also use direct access to set/get item:
localstorage.names = JSON.stringify(names);
var storedNames = JSON.parse(localStorage.names);