I have the below user information.
[ { ID: '21',NAME: 'JACK',MARKS: 75,GRADE: 'A',RESULT: 'PASS ' },
{ ID: '21',NAME: 'JACK',MARKS: 32,GRADE: 'F',RESULT: 'FAIL' },
{ ID: '87',NAME: 'SAM',MARKS: 91,GRADE: 'A+',RESULT: 'PASS' },
{ID: '7',NAME: 'TOM',MARKS: 100,GRADE: 'A+',RESULT: 'PASS' },
{ ID: '21',NAME: 'JACK',MARKS: 61,GRADE: 'B',RESULT: 'PASS' },
{ ID: '87',NAME: 'SAM',MARKS: 72,GRADE: 'B',RESULT: 'PASS ' }
]
Goal is to generate a new object called INFO with fields MARKS,GRADE,RESULT. Also since there are repetitive id's this INFO propery needs to be grouped with its respective id and generate the below result
[{ID:'21',INFO:[{MARKS: 75,GRADE: 'A',RESULT: 'PASS ' },{MARKS: 32,GRADE: 'F',RESULT: 'FAIL'},{MARKS: 61,GRADE: 'B',RESULT: 'PASS']},
{ID:'87',INFO:[MARKS: 91,GRADE: 'A+',RESULT: 'PASS'],[MARKS: 72,GRADE: 'B',RESULT: 'PASS ']},
{ID:'7',INFO:{ MARKS: 100,GRADE: 'A+,RESULT: 'PASS'}
]
I am trying to use the below code but it doesn't generate the expected results
console.log(groupByField(data,'id'))
function groupByField(data, field) {
var outObject = data.reduce(function (a, e) {
let estKey = (e[field]);
(a[estKey] ? a[estKey] : (a[estKey] = null || [])).push(e);
return a;
}, {});
return outObject
}
can someone help me?