Store JavaScript objects in Local Storage
This post will discuss how to store JavaScript objects in localStorage.
The HTML5 localStorage is a recent addition to the standard. With HTML5, you can start using the localStorage.setItem() and localStorage.getItem() to add, change, or fetch data from the local storage.
|
1 2 3 4 5 |
// Save or update the name to the local storage localStorage.setItem("name", "Tom Cruise"); // Read name back from the local storage alert("name = " + localStorage.getItem("name")); |
Note that localStorage supports only the keys and values that are string. To extend the solution for objects, you can stringify the object before saving it in local storage and then parse it while retrieving. This can be easily done using the JSON.stringify() and JSON.parse() methods.
|
1 2 3 4 5 6 7 8 9 10 11 |
const browsers = [ { name: 'Chrome', company: 'Google' }, { name: 'Firefox', company: 'Mozilla' }, { name: 'Safari', company: 'Apple' }, { name: 'Edge', company: 'Microsoft' } ]; localStorage.setItem('browsers', JSON.stringify(browsers)); var localStorageObject = localStorage.getItem('browsers'); console.log(JSON.parse(localStorageObject)); |
You can further extend the Storage.prototype with the following extension methods:
|
1 2 3 4 5 6 7 8 |
Storage.prototype.setObject = function(key, value) { this.setItem(key, JSON.stringify(value)); } Storage.prototype.getObject = function(key) { var value = this.getItem(key); return JSON.parse(value); } |
Here’s an alternative syntax to set or get a key: localStorage.key = value and localStorage.key. Here’s how code would look like:
|
1 2 3 4 5 6 7 8 9 10 11 |
const browsers = [ { name: 'Chrome', company: 'Google' }, { name: 'Firefox', company: 'Mozilla' }, { name: 'Safari', company: 'Apple' }, { name: 'Edge', company: 'Microsoft' } ]; localStorage.browsers = JSON.stringify(browsers); var localObject = localStorage.browsers; console.log(JSON.parse(localObject)); |
It should be noted that JSON.stringify() can’t deal with the circular references and throws a TypeError (“cyclic object value”) exception.
–> starting at object with constructor ‘Object’
— property ‘circular’ closes the circle
at JSON.stringify (
That’s all about storing JavaScript objects in Local Storage.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)