Below is a compilation of items found within the JavaScript object that include the data from the previous list

I am currently experiencing an issue where the values in the list of objects within some object only contain values from the last object.

My goal is to assign scores to locations based on various criteria (which are stored in a separate list). To simplify, I am assigning random numbers as scores to the criteria.

Below is the generated list output where the totalScore should be the sum of all scores in the criteriaScore list. It's evident that the score values in the criteriaScore for 'Location 1', 'Location 2' are reflecting the values of 'Location 3'. This can also be seen in the code snippet following this output.

[
  {
    name: 'Location 1',
    score: {
      totalScore: 113,
      criteriaScore: [
        {
          description: 'Description of Criteria 1....',
          score: 31
        },
        {
          description: 'Description of Criteria 2...',
          score: 29
        },
        {
          description: 'Description of Criteria 3...',
          score: 49
        }
      ]
    }
  },
  {
    name: 'Location 2',
    score: {
      totalScore: 52,
      criteriaScore: [
        {
          description: 'Description of Criteria 1....',
          score: 31
        },
        {
          description: 'Description of Criteria 2...',
          score: 29
        },
        {
          description: 'Description of Criteria 3...',
          score: 49
        }
      ]
    }
  },
  {
    name: 'Location 3',
    score: {
      totalScore: 30,
      criteriaScore: [
        {
          description: 'Description of Criteria 1....',
          score: 31
        },
        {
          description: 'Description of Criteria 2...',
          score: 29
        },
        {
          description: 'Description of Criteria 3...',
          score: 49
        }
      ]
    }
  }
]

In the code snippet below, the mentioned output is being produced. Can anyone point out what may be wrong with my approach here? Thank you!

// Here lies the initial list of criteria used for location assessments
let criteriaList = [
  {
    description: 'Description of Criteria 1....'
  },
  {
    description: 'Description of Criteria 2...'
  },
  {
    description: 'Description of Criteria 3...'
  }
];

// Names of locations which will receive scores based on the above criteria list
let locationList = [
  {
    name: 'Location 1'
  },
  {
    name: 'Location 2'
  },
  {
    name: 'Location 3'
  }
];

const calcAllLocationsScore = () => {
  let locationScoreList = [];
  locationList.forEach(location => {
      locationScoreList.push({
        ...location,
        score: calcLocScore()  
      });
  });
  
  return locationScoreList;  
};

const calcLocScore = () => {
  let locScore = {
    totalScore: 0,
    criteriaScore: [] 
  }
  let index = 0;
  criteriaList.forEach(criteria => {
    criteria.score =  Math.floor((Math.random() * 50) + 0);
    locScore.totalScore += criteria.score;
    locScore.criteriaScore.push(criteria);
  });
    
  return locScore;
};

calcAllLocationsScore();

Answer №1

Your criteriaList contains 3 criteria with scores that are being overwritten for each location. The criteriaScore array also only stores references to these 3 criteria, resulting in the final set of scores being the same across all locations.

To address this issue, modify your criteria list loop to create new criteria objects every time:

criteriaList.forEach(criteria => {
    const newCriteria = {...criteria};
    newCriteria.score = Math.floor((Math.random() * 50) + 0);
    locScore.totalScore += newCriteria.score;
    locScore.criteriaScore.push(newCriteria);
});

It is unclear why the totalScore value in your example is 30 when the individual scores add up to 109. This discrepancy suggests that the displayed output may not be accurate.

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

What is the process for creating a login page that redirects automatically?

For instance: Whenever I enter gmail.com, it automatically takes me to this link: https://accounts.google.com/signin/v2/identifier?service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ss=1&scc=1&ltmp ...

Conceal a secret input element's value upon clicking a submit button (using PHP and jQuery)

Greetings, I'm facing an issue and need your assistance: Here's the scenario - I have a form that gathers First Name, Last Name, and City from the user. Upon clicking submit, the provided information is then showcased within a table as follows: ...

Encountered a parsing error when attempting to integrate SCSS with webpack and babel setup

I am facing an issue while trying to integrate SCSS into my webpack and babel setup. When running npm run build, I encounter an error that I'm unfamiliar with. As a beginner in using webpack and babel, I'm unsure about the necessary changes requ ...

What are the implications of utilizing props value with a React hook?

Recently diving into the world of React hooks, I've come across a new pattern that isn't covered in the official documentation: const MyComponent = ({myProp}) => { const [myPropHook, setPropHook] = useState(myProp) ... } Is this approach co ...

Assistance is needed in resolving conflicts where array keys are being overwritten

Currently experiencing an issue with an array being returned from a query I executed, $jobs = array( array('id'=>2,'salary'=>27000,'benefits'=>'false','benefits_description'=>'&apos ...

Importing JWT in ES6SyntaxCreating ES6 imports

I'm currently developing a nodeJS web application and utilizing JWT for authentication. My code is all written in ES6 modules, so I wanted to import JWT the same way. However, it seems that the package does not fully support this method yet. Since I&a ...

Encountering issues with retrieving a specific document from DocumentDB in Node.js

My goal is to retrieve a specific document from DocumentDB using the document ID. The collection consists of four fields, with author serving as the partition key. { "id": string, "author": string, "title": string, "year": int } I have implemente ...

Is it possible to use a Jade block extension for every individual item in the database?

What's the issue here? test.jade doctype !!! 5 html(lang="en-us") head title test h1 Information; body block testcontent form(method="post") input(type="button", value="refresh") testcontent.jade ...

jQuery fails to operate on products loaded through AJAX requests

Upon opening the page, jQuery functions correctly. However, when a product is loaded or changed via AJAX, jQuery stops working. I am currently using jquery-1.7.1.min.js $(document).ready(function () { $screensize = $(window).width(); if ($screensi ...

The Javascript setTimeout Function Prolongs Its Operation

Currently, I have a web app index page that performs two main tasks. Firstly, it geocodes the user's location and stores it in a JavaScript variable called "variableToSend." Secondly, it sends this data to mySQL using a PHP script after a delay of 10 ...

How can we properly access the DOM element generated by an {#each} loop in Svelte when it is clicked?

Using Svelte's {#each} functionality, I am reactively loading elements in the following way: {#each $items as item} <div> <Button on:click={someFunction}>{item.text}</Button> (*) </div> {/each} (*) a component t ...

Using AJAX with the GET method, send a form submission to retrieve a response using XMLHTTPRequest

I am working on a form where users can select values from two dropdown menus. The options in the dropdowns are populated dynamically from a JavaScript file, which contains a list of exchange rates. I have written the code to calculate and display the resul ...

Converting a JavaScript animation into a video through server-side processing: A step-by-step guide

Attempting to tackle a challenging task but willing to give it a shot: Our team is currently working on developing a website that enables users to generate animations using javascript and html. However, our latest client request involves uploading the cre ...

Exploring the world of cookie security with SameSite and Secure features in ExpressJS

Despite having the specified settings on my express application, a warning keeps appearing in the console. Has anyone encountered this error before? I found some information related to it here: https://github.com/expressjs/express/issues/3095 The version ...

Is there a way to make the sidepanel appear and be edited with just one click on a Chrome extension, instead of the current two-click requirement?

Currently, I am in the process of developing a Chrome dictionary game extension. In the initial phase of the project, the user should have the ability to right-click on a word, triggering the display of a side panel containing definitions sourced from a lo ...

Troubleshooting Issue: jQuery Popup Functionality Not Functional in ASP.NET Core 2.2

I'm having trouble with creating a popup form to add employees or categories. When I click the "Create" button, nothing happens. Take a look at my code: namespace EasyBay.Areas.Admin.Controllers { [Area("Admin")] public class CategoryControll ...

The search function in Typeahead is not activating the API request while typing

Having some trouble implementing a typeahead search feature in my nodejs application with mysql. I can't seem to figure out what's wrong with my code. When I manually access http://localhost:5000/search?key=s, I'm able to see the results an ...

"Wordpress Pluto theme: A stellar choice for your

I'm trying to add a link in my main template.index file that will redirect to one of my pages when clicked on the JavaScript button at the top in Pluto theme. Currently, the text is there but clicking on it opens something I don't want. Here&apo ...

Tips on retrieving a <list> from an MVC controller and passing it to the view with jQuery and AJAX

How can I retrieve a list from an MVC controller to a view using jQuery AJAX without getting the error message [object Object]? Here is my AJAX code: $.ajax({ type: 'POST', contentType: 'application/json; ch ...

Issue with Vue Composition API: Unable to append a property to an object

Currently, I am utilizing Vue's Composition API in my project. However, I have encountered an issue where the template renderer does not recognize changes when I add a property to a ref object. Below is the code snippet that demonstrates this problem: ...