所以我有两组数据:
第一个数据是考试的答案
第二个数据是参加考试的学生的答案
根据这两个数据,我试图对它们进行排列映射。
const answerKey = [{
id: "bida01",
answerKey: "b",
category: "bida",
nomorSoal: "01",
score: 20
},
{
id: "bida02",
answerKey: "b",
category: "bida",
nomorSoal: "02",
score: 30
}
]
const participants1 = [{
answers: {
bida01: "a",
bida02: "b",
bida03: "c",
},
category: "bida",
firstName: "John",
lastName: "Collins",
school: "Something Junior High",
address: "Somewhere",
email: "blabla@bla.com"
},
{
answers: {
bida01: "b",
bida02: "b",
bida03: "a",
},
category: "bida",
firstName: "Jennifer",
lastName: "Harley",
school: "Somewhere Junior High",
address: "Also somewhere",
email: "notsure@bla.com"
}
]
const answerKeyData = answerKey.map((elem) => {
console.log(elem.id, elem.answerKey, elem.score);
})
const participantData = participants1.map((elem, idx) => {
console.log(elem.answer, elem.firstName, elem.middleName, elem.lastName, elem.school);
});
现在我可以从这些console.log的结果中看到,我可以得到我想要比较的值。我在这里的目的是比较学生的答案和答案键,然后如果它们匹配:
return score += elem.score
但是我如何访问elem.id,elem.answerKey,elem.score?我应该用它们创建一个新对象(比如objectAnswerKey(吗?我该怎么做?
elem.firstName、elem.middleName、elem.lastName、elem.school和elem.answer也是如此。我应该创建一个新对象(比如objectAnswer(,然后比较objectAnswers和objectAnswerKey吗?
或者有更简单的方法吗?
您可以使用嵌套的map/forEach/reduce数组方法,通过比较问题id和answerKey来计算分数,如下所示,
const participantsWithScore = participants1.map(student => {
const answers = student.answers;
const questions = Object.keys(answers);
let score = 0;
questions.forEach(question => {
const answer = answers[question];
const correctAnswer = answerKey.find(key => key.id === question);
if(correctAnswer && correctAnswer.answerKey === answer) {
score += correctAnswer.score;
}
});
student.score = score;
return student;
});
console.log(participantsWithScore);
在控制台中,您可以看到所有参与者都具有计算分数属性。
const answerKey = [
{
id: "bida01",
answerKey: "b",
category: "bida",
nomorSoal: "01",
score: 20
},
{
id: "bida02",
answerKey: "b",
category: "bida",
nomorSoal: "02",
score: 30
}
];
const participants1 = [
{
answers: {
bida01: "a",
bida02: "b",
bida03: "c"
},
category: "bida",
firstName: "John",
lastName: "Collins",
school: "Something Junior High",
address: "Somewhere",
email: "blabla@bla.com"
},
{
answers: {
bida01: "b",
bida02: "b",
bida03: "a"
},
category: "bida",
firstName: "Jennifer",
lastName: "Harley",
school: "Somewhere Junior High",
address: "Also somewhere",
email: "notsure@bla.com"
}
];
const handleCalculate = () => {
const studensScore = [];
participants1.forEach((student) => {
let score = 0;
answerKey.forEach((answerKeyItem) => {
const userAnswer = student.answers[answerKeyItem.id];
if (userAnswer === answerKeyItem.answerKey) {
score += answerKeyItem.score;
}
});
const studentData = {
fullname: student.firstName + " " + student.lastName,
score: score
};
studensScore.push(studentData);
});
return studensScore;
};
console.log(handleCalculate())