I am trying to store localStorage value in array and following this page Push JSON Objects to array in localStorage. My code is:
function SaveDataToLocalStorage(data)
{
var a = [];
// Parse the serialized data back into an aray of objects
a = JSON.parse(localStorage.getItem('session'));
// Push the new data (whether it be an object or anything else) onto the array
a.push(data);
// Alert the array value
alert(a); // Should be something like [Object array]
// Re-serialize the array back into a string and store it in localStorage
localStorage.setItem('session', JSON.stringify(a));
}
where data
is:
var data = {name: "abc", place: "xyz"}
I am getting the following error:
Uncaught TypeError: Cannot call method 'push' of null
Can anybody show the correct method to store localStorage values in array?