Recently while working I had a requierment to save a JavaScript array in local storage of HTML 5. Let us say the array is as the follwing that we want to save in local storage:
var movieArray = [
{ title: "The Artist", picture: "images/TheArtist.jpg" },
{ title: "A Better Life", picture: "images/abetterlife.jpg" },
{ title: "Abduction", picture: "images/abduction.jpg" },
{ title: "African Cats", picture: "images/africancats.jpg" },
{ title: "Angel Crest", picture: "images/angelscrest.jpg" },
{ title: "Arthur", picture: "images/arthur.jpg" },
{ title: "Anonymous", picture: "images/anonymous.jpg" },
{ title: "A Dangerous Method", picture: "images/adangerousmethod.jpg" },
];
Before saving, iterate through the array and display in the console. We can display on the console as in the follwing:
To see the console, log in to the Chrome browser, press F12 and select the console tab.
Everything is fine as of now and we can go ahead and save the data in local storage as in the follwing:
As of now we have saved the data and fetched as well. Let us try to display the fetched data:
In output windows you will be getting some expected data as in the following:
On matching you will find that the type of the original array was object whereas the type of the reterived data is string. This is where the problem lies; that HTML5 stores data as a string. So before saving data you need to stringify the array object and after reteriving the data you need to parse the string as a JSON object. Saving and reteriving will be modified as in the followling:
Now if you print the reterived result you should be getting the expected output. The full code to save and reterive is as follows:
var movieArray = [
{ title: "The Artist", picture: "images/TheArtist.jpg" },
{ title: "A Better Life", picture: "images/abetterlife.jpg" },
{ title: "Abduction", picture: "images/abduction.jpg" },
{ title: "African Cats", picture: "images/africancats.jpg" },
{ title: "Angel Crest", picture: "images/angelscrest.jpg" },
{ title: "Arthur", picture: "images/arthur.jpg" },
{ title: "Anonymous", picture: "images/anonymous.jpg" },
{ title: "A Dangerous Method", picture: "images/adangerousmethod.jpg" },
];
console.log('typeof movieArray: ' + typeof movieArray);
console.log('movieArray:');
for (var p in movieArray) {
console.log(p+':'+movieArray[p].title+'|'+movieArray[p].picture);
}
localStorage.setItem('movieArray', JSON.stringify(movieArray));
var retrievedMovieArray = JSON.parse(localStorage.getItem('movieArray'));
console.log('typeof retrievedMovieArray: ' + typeof retrievedMovieArray);
console.log('retrievedMovieArray:');
for (var p in retrievedMovieArray) {
console.log(p +':'+ retrievedMovieArray[p].title +'|'+retrievedMovieArray[p].picture);
}
});
In this way we can save and reterive JavaScript objects in the local storage of HTML5. I hope this article is useful. Thanks for reading.