I have three arrays: students, type, and marks. I want to combine these into one array called student_marks to get each student's marks with mark types. But the object mark function is returned as a string and is not executed in javascript as shown in the picture code result.
I want to get this result:
{student: '2'; totalmarks: '0'; mark: {'typeid'="marks" ,'typeid'="marks" , 'typeid'="marks" }}
So as a whole the result array which is student_marks will look like:
{student: '2'; totalmarks: '0'; mark: {'1'="1" ,'2'="2" , '3'="3" }}
{student: '3'; totalmarks: '0'; mark: {'1'="5" ,'2'="4" , '3'="7" }}
{student: '4'; totalmarks: '0'; mark: {'1'="8" ,'2'="7" , '3'="9" }}
Here is my code sample is written in js:
let std = [
1, 2, 3, 4
];
let marks = [{
type: '2',
marks: '2'
}, {
type: '1',
marks: '1'
},
{
type: '3',
marks: '3'
}, {
type: '2',
marks: '2'
},
{
type: '1',
marks: '1'
}, {
type: '3',
marks: '3'
},
{
type: '2',
marks: '2'
}, {
type: '1',
marks: '1'
},
{
type: '3',
marks: '3'
}, {
type: '2',
marks: '2'
},
{
type: '1',
marks: '1'
}, {
type: '3',
marks: '3'
}
];
let type = [2, 1, 3];
let ri = 0;
let student_marks = [];
let registrationIds = [];
let total_marks = [];
std.forEach(item => {
registrationIds[ri] = item;
// type[ri]=marks[ri];
// marks:marks[ri];
student_marks.push({
student: item,
mark: () => {
for (let i = 0; i < marks_type.length; i ) {
// m[marks_type[i]]=marks[i][ri];
m = [{
type: marks_type[i],
marks: marks[i]['marks'],
}];
// m:{
// marks_type[i]=marks[i][ri];
// };
}
console.log(m);
return m;
},
// totalmarks: total_marks[ri].value,
});
// totalmark[ri]=total_marks[ri].value;
ri ;
});
console.log(student_marks);
CodePudding user response:
Since JavaScript functions are first class citizens, meaning it is treated similar to variables, the function in mark
inside the object student_marks
is assigned to it and not executed. Also note that the returned value is a function which you have mentioned a string. For your code to work,
- Method 1:
Wrap that function somewhere and just call it instead.
const calculateMark = () => {
for (let i = 0; i < marks_type.length; i ) {
// m[marks_type[i]]=marks[i][ri];
m = [{
type: marks_type[i],
marks: marks[i]['marks'],
}];
// m:{
// marks_type[i]=marks[i][ri];
// };
}
console.log(m);
return m;
};
student_marks.push({
student: item,
mark: calculateMark()
// totalmarks: total_marks[ri].value,
});
- Method 2:
Use IIFE
student_marks.push({
student: item,
mark: (() => {
for (let i = 0; i < marks_type.length; i ) {
// m[marks_type[i]]=marks[i][ri];
m = [{
type: marks_type[i],
marks: marks[i]['marks'],
}];
// m:{
// marks_type[i]=marks[i][ri];
// };
}
console.log(m);
return m;
})(),
// totalmarks: total_marks[ri].value,
});