Recently while working I had a requierment to save Javascript array in local storage of HTML5. Let us say array is as follwing 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 array and display in the console. We can display on console as following
To see console log in chrome browser press F12 and select console tab.
everything is fine as of now and we can go ahead and save the data in local storage as following ,
As of now we have save data and fetched as well. let us try to display fetched data
in output windows you will be getting some expected data as following,
on matching you will find that type of original array was object whereas type of retrieve data is as string. This is where problem lies that HTMl5 stores data as string. so before saving data you need to stringify the array object and after retrieving data you need to parse the string as JSON object. saving and retrieving will be modified as following
now if you print retrieved result you should be getting the expected output. Full code to save and retrieve is as following ,
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 retrieve Javascript object in local storage of HTML5. I hope this post is useful. Thanks for reading.
Follow @debug_mode