Skip to content
Advertisement

How can I preserve array references when loading a similar but new array?

I’ve been fiddling around with javascript making a game, and while trying to create a save/load mechanism I’ve come into some trouble.

This could potentially come from how the game is set up, but primarily I’m going to describe the gameData that is saved and loaded in an abstracted example.

let farm = {
  amount: 0
}

let hut = {
  amount: 0
}

let gameData = {
  buildingArray: [farm, hut]
}

function saveGame() {
    let saveData = gameData
    localStorage.setItem(localStorageName, JSON.stringify(saveData))
    console.log("Data Saved")
}

function loadGame() {
    if (localStorage.getItem(localStorageName)) {
        loadData = JSON.parse(localStorage.getItem(localStorageName))
        gameData = loadData
        console.log("Data Loaded")
    }
}

To save and load this, I am simply storying the JSON of gameData in local storage and then parsing it to load.

The main issue I’m having from this is when gameData is loaded, with say farms and huts of amount 1. The gameData object will reflect this, but the individual farm and hut objects will still show an amount of 0.

In my project I declare all of these variables separately and then associate them all together in gameData for readability, and perhaps that implementation is reckless, so if there is a way to fix this issue and reorganize, that would also be appreciated.

The reason why this is confusing me is because until the game is loaded, these referenced objects will update if for example a farm is purchased. After loading, it seems like the references stored in the array are decoupled and I was wondering – is there a way to fix this?

Advertisement

Answer

In your loadData function you could add an assignment to farm and hut so they are synchronised with the loaded data:

gameData = loadData;
[farm, hut] = gameData.buildingArray; // <--- add this

However, I would suggest you use a more OOP approach, avoiding such global variables:

class Game {
    static localStorageName = "myGame";
    constructor() {
        this.farm = 0;
        this.hut = 0;
    }
    save() {
        localStorage.setItem(Game.localStorageName, JSON.stringify(this))
        console.log("Data Saved");
    }
    load() {
        let loadData = localStorage.getItem(Game.localStorageName);
        if (loadData) {
            Object.assign(this, JSON.parse(loadData));
            console.log("Data Loaded")
        } else {
            console.log("No data to load")
        }
    }
}

// Example run
let game = new Game();
game.hut++;
game.save();
game.hut = 0;
game.load();
console.log(game.hut); // 1
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement