I am facing a challenge with my student object structure...
{
Freshmen: [{id: 3}, {id: 5}],
Sophomores: [{id: 2}, {id: 6}],
Juniors: [{id: 1}, {id: 8}],
Seniors: [{id: 9}, {id: 4}, {id: 7}]
}
My goal is to retrieve full student objects from the database based on the ids in the arrays. The desired output should maintain the same object structure.
In my angular component.ts file, I have attempted to achieve this as follows...
private getStudents(obj) {
const result = {};
for (const key of Object.keys(obj)) {
obj[key].map(item => {
this.studentsService.geStudentById(item.id).subscribe(res => {
result[key] = [];
result[key].push(res);
});
});
}
return result;
}
I have injected a service into the component which has a method to fetch student details by id. I call this method within getStudents()
. The service returns student objects that I push into the array.
After calling the function, I assign the results to a variable studentDetails
like so...
this.studentDetails = this.getStudents(studentObj);
Although everything seems fine, when I try to access
console.log(this.StudentDetails.Freshmen);
, it returns undefined
.
I am wondering if there is a more efficient way to handle this situation, such as using arr.reduce()
instead of arr.map()
? I did try reduce but encountered an issue where only one item was returned.
Any advice or suggestions would be highly appreciated.