I have an object which contains the marks of a subject, I am trying to calculate the total of 1st_CQ
and 1st_MCQ
of the subjects dynamically, after 1st CQ and MCQ I want to calculate the 2nd part 2nd_MCQ
& 2nd_CQ
, sometimes there will no MCQ
like the English subject.
const subNums = {
english_1st_CQ : 24,
english_2nd_CQ: 24,
math_1st_CQ: 40,
math_1st_MCQ: 10,
math_2nd_CQ:35,
math_2nd_MCQ:10,
// .....
}
so I have created an Object like this, the idea is to loop the subject and pass the first and second subject numbers into a function and the function will return the total.
const subject = [
{
sub: "english",
first: {
CQ1st: "english_1st_CQ",
MCQ1st: undefined,
},
second: {
CQ1st: "english_2nd_CQ",
MCQ1st: undefined,
},
{
sub: "math",
first: {
CQ1st: "math_1st_CQ",
MCQ1st: "math_1st_MCQ",
},
second: {
CQ1st: "math_2nd_CQ",
MCQ1st: "math_2nd_MCQ",
},
},
}]
I am stuck here, I am not able to store the total number inside a variable, [sub.sub] =
this throws an error that number 32 is not iterable (cannot read property Symbol(Symbol.iterator))
I want to store the totals with their subject Name like this english: 48, math_1st: 50, math_2nd:45
const subTotal = subject.map((sub: any) => {
let obj;
[sub.sub] = calculateTotal(subNums[sub.first.CQ1st], rest[sub.first.MCQ1st]);
});
CodePudding user response:
You don't need to create another object to map data. According to your object model, we can find a pattern {subject name}_{subject position}_{suffix}
in keys.
With that, we can try to find matched combinations to generate results by reduce
const value = {
english_1st_CQ: 5,
english_2nd_CQ: 10,
math_1st_CQ: 15,
math_1st_MCQ: 20,
math_2nd_CQ: 25,
math_2nd_MCQ: 30,
};
const finalResult = Object.entries(value).reduce((result, [key, value]) => {
const [subjectName, subjectPosition, suffix] = key.split('_')
const fullSubjectName = `${subjectName}_${subjectPosition}`
if(!result[fullSubjectName]) {
result[fullSubjectName] = 0;
}
result[fullSubjectName] = value
return result
}, {})
console.log(finalResult)