I would like to know how to Merge properties of objects with in same array of objects if same value in javascript.
My input data
var input = [
{ student: 'Alex', class: 'ten', subject: 'maths', marks: '85', answer: 'Moderate', percentage: '90', sports: 'good' },
{ student: 'Alex', class: 'ten', subject: 'maths', marks: '85', answer: 'Moderate', percentage: '90', sports: 'good' },
{ student: 'Alex', class: 'nine', subject: 'science', marks: '82', answer: 'Severe', percentage: '85', sports: 'good' },
{ student: 'Alex', class: 'nine', subject: 'science', marks: '82', answer: 'Severe', percentage: '85', sports: 'good' },
{ student: 'Alex', class: 'eight', subject: 'computer', marks: '90', answer: 'Extreme', percentage: '87', sports: 'good' },
{ student: 'Alex', class: 'eight', subject: 'computer', marks: '90', answer: 'Extreme', percentage: '87', sports: 'good' },
{ student: 'john', class: 'ten', subject: 'maths', marks: '90', answer: 'Extreme', percentage: '99', sports: 'good' },
{ student: 'john', class: 'ten', subject: 'maths', marks: '90', answer: 'Extreme', percentage: '99', sports: 'good' },
{ student: 'john', class: 'nine', subject: 'science', marks: '85', answer: 'Moderate', percentage: '100', sports: 'good' },
{ student: 'john', class: 'nine', subject: 'science', marks: '85', answer: 'Moderate', percentage: '100', sports: 'good' },
{ student: 'john', class: 'eight', subject: 'computer', marks: '87', answer: 'Extreme', percentage: '67', sports: 'good' },
{ student: 'john', class: 'eight', subject: 'computer', marks: '87', answer: 'Extreme', percentage: '67', sports: 'good' },
]
Expected Output:
[
{ student: 'Alex',class: 'ten', maths: '85', science: '82',computer:'90', answer: 'Moderate', percentage: '90', sports: 'good'},
{ student: 'Alex',class: 'nine', maths: '85', science: '82',computer:'90', answer: 'Moderate', percentage: '85', sports: 'good'},
{ student: 'Alex',class: 'eight', maths: '85', science: '82',computer:'90', answer: 'Moderate', percentage: '87', sports: 'good'},
{ student: 'john',class: 'ten',maths: '90', science: '85',computer:'87',answer: 'Extreme', percentage: '99', sports: 'good'},
{ student: 'john',class: 'nine',maths: '90', science: '85',computer:'87',answer: 'Extreme', percentage: '100', sports: 'good'},
{ student: 'john',class: 'eight',maths: '90', science: '85',computer:'87',answer: 'Extreme', percentage: '67', sports: 'good'},
]
I tried below code
const output = data.reduce((a, v) => {
const key = i.student + i.subject;
const subjectKey = v.subject
if (a[key]) {
a[key] = {
...v,
[subjectKey]: v.marks,
}
} else {
a[key] = v
}
return a
}, {})
console.log(Object.values(output))
answer
s are different for each object) with current expected output. Object structure should be likename:'Alex', courses:[{subject:'Math',marks: '90', answer: 'Extreme' }, {subject:'Science',marks:'90',answer: 'Moderate' }]
... Also student name can be same, there must be some identifier.