HTML5 localStorage lets you store key/value pairs of data. Both key and value needs to be a string.
To store objects as a key or value you need to encode the object into a JSON string. And while retrieving you need to decode it back to an object.
Here is example code
var object = {
x: 12,
y: 56
}
localStorage.setItem("object", JSON.stringify(object));
object = JSON.parse(localStorage.getItem("object"));
console.log(typeof object); //object
console.log(object); //Object {x: 12, y: 56}
x: 12,
y: 56
}
localStorage.setItem("object", JSON.stringify(object));
object = JSON.parse(localStorage.getItem("object"));
console.log(typeof object); //object
console.log(object); //Object {x: 12, y: 56}
Leave a Reply