What is the best way to add a new value to an object without replacing the existing one in the key-value pair?

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!

Answer №1

I personally believe restructuring the playerData would be beneficial. My suggestion is to format it like this: {player_1: 90, player_2: 80}.

This way, each player has a key-value pair where the key represents the player and the value represents their score.

You can stringify this data and store it in local storage easily. When adding a new player, you can simply do:

playerData['player_3'] = 50, resulting in playerData becoming:

{player_1: 90, player_2: 80, player_3: 50}
.

This approach solves the issue of adding players without overwriting existing ones.

Your previous structure may have been designed for sorting purposes. However, you can still create a leaderboard by following these steps:

// Convert the data to a list.
leaderbord = []
for (playerScore in playerData) {
    leaderbord.push([playerScore, playerData[playerScore])

// Sort the list based on the second element of each element.
for (playerScore in playerData) {
    leaderbord.push([playerScore, playerData[playerScore]])
    leaderbord.sort((a,b) => b[1]-1[1])
}

Answer №2

One approach is to use the username as a unique identifier and assign the score as its corresponding value

const userScores = {};
let username1 = 'fernando';
userScores[username1] = 45;
let username2 = 'luis';
userScores[username2] = 5;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Queries surrounding the use of useState in React.js function components

I am having trouble accessing state data. Can someone guide me on how to transfer an array object into a data array? -code function TableList() { const [state, setState] = React.useState({ columns: [ { title: '로트번호', field ...

Using jQuery to locate the closest class and display a div

Currently facing an issue with toggling on my webpage. I have a series of yes and no questions, and based on the user's response, additional questions should appear. Everything was functioning properly until I needed to relocate some of these question ...

Encountering a challenge in React where state cannot be modified while developing a Like Button

When creating a like/dislike component for comments, I encountered an issue with maintaining the state on the initial run. Initially, it returns undefined, but the state updates after pressing the like button for the second time. Below is the JSX code snip ...

Transforming a JSON file that has been previously converted to an Observable into a TypeScript map within an Angular application

There is a json data file named dummy, with the following structure: [ {"key":"KEY1", "value":["alpha","beta","gamma"]}, {"key":"KEY2", "value":["A","B","C"]}, {"key":"KEY3", "value":["One","Foo","Bar"]} ] The goal is to convert this json f ...

Validating forms using Jquery before submitting data through Ajax across multiple forms

Despite being a common issue, I have tried multiple solutions without success. The problem with jQuery validation persists even before the AJAX call is made. The form submits without any validation taking place. Please help me identify where I may be goin ...

How to resolve a Cross-Origin Resource Sharing (CORS) error when trying to access a local JSON file

Currently, I am attempting to use vanilla JS AJAX request in order to retrieve a JSON string from a locally stored JSON file. My main objective is to accomplish this without relying on JQuery. The code snippet below was inspired by this answer. Despite my ...

Tips for positioning text on the left and right sides of a div in HTML styling

I am struggling with positioning two pieces of text within a div. Despite having some styling already in place, the text is currently displaying one after the other on the left-hand side. I want to position one piece of text to the left and another to the ...

Searching for a way to display just a portion of a rendered HTML page using JavaScript

With the JavaScript code window.print(), it is possible to print the current HTML page. If there is a div in an HTML page (such as a page generated from an ASP.NET MVC view), the aim may be to only print that specific div. Is there any jQuery unobtrusive ...

Each slider only displays a single database entry

I have an array that retrieves testimonials from a database table and displays them using a foreach loop. I am looking to implement a slider that can fade in and fade out the results. Here is my database query: $showTestimonials = array(); $getTestimoni ...

Building an Empty AngularJS Response with the Combination of Spring Boot and MongoDB

In my AngularJS application, I collect user input and store it in painting objects. These objects are then sent to my Spring Boot backend which saves them to a MongoDB server and returns an ID. However, when attempting to POST data to the server, I receive ...

Achieve the effect of making the Bootstrap JS Collapse text bold after it has been

Is there a way to make Bootstrap JS Collapse text Bold after it has been clicked on? <tr data-toggle="collapse" data-target="#demo8" class="accordion-toggle"> <td> <div class="fa ...

Reduce the size of the profile picture in the Facebook like box

I have a Facebook like box on my site but in some resolutions the profile pictures goes to next line after 2 pictures instead of 3 so I want to make the profile pictures width and height 49 instead of 50 because that would fix the problem. Here's how ...

Learn how to extract an ID created with AngularJS using JavaScript

I have a piece of code that generates multiple divs using ng-repeat and assigns each one an id based on a specific value. <div ng-repeat="item in $scope.items"> <div id="ajs-{{item.title}}">{{text}}</div> <script> v ...

Nuxt middleware failing to verify user's logged-in status

I am currently working on implementing user authentication and redirection logic based on the user's authentication status. For instance, if a logged-in user tries to access the login or signup page, they should be automatically redirected. To achieve ...

Instead of modifying the selected class, jQuery generates inline styles

Utilizing the following code to dynamically create a class: $("head").append('<style type="text/css"></style>'); var newStyleElement = $("head").children(':last'); newStyleElement.html('.move{transform: translateX(1 ...

What is the best way to bring a list from one .js file into my main.js file?

Here is a demonstration using Ania Kubow's Climate change API. My query is: I have a lengthy list similar to this one, and I would like to store it in a separate file named "exampleList.js" and then import it into my main.js file. const newspapers = ...

Having difficulty accessing the API response accurately

The response from my API is as follows: {"__v":0,"short":"8xdn4a5k","_id":"5404db5ac27408f20440babd","branches":[{"version":1,"code":""}],"ext":"js","language":"javascript"} When I use this code, it works perfectly: console.log(response.short); However ...

What is the best way to restrict the maximum number of items stored in local storage?

I'm creating a GitHub search app using the GitHub API in Angular. I want to restrict the number of items that can be stored in local storage. If the number of stored elements exceeds 5, the "Add to Favorite" button should either stop working or disapp ...

What is the best way to extract the ID from a dynamic "ul" tag?

Let me explain the scenario I'm facing. Currently, I have a button in my HTML code that triggers a function to generate content from another button upon selection. In the HTML code, there is a ul tag containing li tags which are populated dynamically ...

Avoid the problem of animations triggering twice when clicking

Hey there, I am facing an issue with my slider. If you could take a look at this website , you will notice that after clicking on the arrows, the slider behaves asynchronously. It changes speed rapidly at times and then slows down, repeating this pattern ...