My question is regarding using localStorage
for a page. I've been making a game in JavaScript, and as it's quite a lengthy one to play, one problem has been that too often the tab is accidentally closed or the computer shut down before its completion. Therefore, I'm hoping to work out some sort of simple game save procedure so that such events will not cause the whole game to reset.
The data that I need to store consists of three arrays and one primitive value. Each of these are created when the user begins playing the game, and as the game is played, objects will be added to the arrays, and the primitive value- an integer- is incremented. The integer value should not be difficult, but the arrays consist of objects, rather than primitive values, and so JSON.stringify
only literally returns "[object Object, object Object, object Object (...)]"
as a string.
I've tried iterating over the arrays and stringifying each of the objects individually, but that seems sort of convoluted, I can't quite think round it, and besides, I seem to have done something wrong and it doesn't work regardless.
Here is the relevant moiety of the program thus far, if anyone wants to see for whatever reason:
var frogarray = [parent1, parent2, parent3, parent4]
var nestarray = [nest1]
var genesisarray = [];
pushGenesis( new Genesis() );
var boondollars = 0;
function getProgress () {
var frogdata = localStorage.getItem("frogs");
var nestdata = localStorage.getItem("nests");
var boondata = localStorage.getItem("boondollars");
var genesisdata = localStorage.getItem("genesis");
frogarray = JSON.parse( frogdata );
nestarray = JSON.parse( nestdata );
genesisarray = JSON.parse( genesisdata );
boondollars = boondata;
frogtoUI();
nesttoUI();
printboons();
}
function saveProgress() {
var storagefrog = [];
var storagenest = [];
var storagegenesis = [];
function stringifying ( array, name, storagearray ) {
for ( i = 0; i < array.length; i++ ) {
var s = JSON.stringify( array[i] );
storagearray.push(s);
localStorage.setItem(name, JSON.stringify(storagearray));
}
}
stringifying(frogarray, "frogs", storagefrog)
stringifying(nestarray, "nests", storagenest)
stringifying(genesisarray, "genesis", storagegenesis)
localStorage.setItem("boondollars", boondollars)
}
Is there any way that I can retrieve and store arrays of objects in localStorage
correctly- a simpler or cleaner way, if possible?
Edit:
Here's an example of an object from each array:
frogarray or genesisarray:
parent1 = {
gender: "female",
colour: "red",
eyecolour: "blue",
pattern: "plain",
sized: "small",
}
nestarray:
nest1 = {
typ: "normal",
nestTime: 0,
frog1: "",
frog2: "",
currentbreed: false,
}