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 score
s 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();