Currently, I am in the process of developing an application that will save and display a user's name and score. The main challenge I am facing is figuring out how to update the existing data with new information without losing the previous entries. Below is a snippet of the relevant code:
// persistence
savedPlayerData = JSON.parse(localStorage.getItem("playerData") || "[]");
function storePlayerData() {
localStorage.setItem("playerData", JSON.stringify(playerData));
}
// player name and score object
const playerData = {playerName: "", score: ""}
// function for updating the playerData object...
// ...once the save button is clicked in another part of my script
function setPlayerNameAndScore() {
username = playerName.value
playerNameLabel.classList.add("hide");
playerName.classList.add("hide");
saveScoreButton.classList.add("hide");
playerData["playerName"] = username;
playerData["score"] = finalScore
storePlayerData();
}
Currently, each time a user chooses to save their name and score, the storePlayerData()
function simply overwrites any previously saved data. Ideally, I would like to have a structure where multiple player names and scores can be stored and associated correctly. This way, I can later showcase them on a high scoreboard.
How can I modify my local storage data to resemble this format?
const playerData = {playerName: "player1", "player2", score: "90", "100"}
. Any advice or guidance on achieving this functionality would be greatly appreciated!