I have a student object that looks like this...
{
Freshmen: [{id: 3}, {id: 5}],
Sophomores: [{id: 2}, {id: 6}],
Juniors: [{id: 1}, {id: 8}],
Seniors: [{id: 9}, {id: 4}, {id: 7}]
}
I need to do a look up for students based on the ids in the arrays. What I need to be returned is an object that looks exactly the same but where instead of the objects containing just the ids, I now have the full object retrieved from the database.
Inside my angular component.ts file, I am attempting to do so in the following way...
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 a service injected into the component. The service has a method which gets students by the id and I'm calling the service method inside getStudents()
. The service returns the respective student objects which I am then pushing into the array.
Later I am calling the function and assigning the results to a variable studentDetails
like so...
this.studentDetails = this.getStudents(studentObj);
Everything seems to be working fine except that when I try to do... console.log(this.StudentDetails.Freshmen);
for example, I get undefined
.
Am I going about this the right way or is there some better way I could handle it, like maybe using arr.reduce()
instead of arr.map()
? Although I have tried reduce and it only returns one item for some reason.
Your help would be greatly appreciated.