I am calling the backend with this http call:
this.StudentEnrollment.getRecordsById(list.value.split(/[\r\n]+/)).subscribe(values => {
this.studentObject = values;
});
studenObject looks like this
{
records: [{name: james, school: USC, .....}, {name: Micheal, school: UCLA, ......},{name:
John, school: UCLA, ......}],
size: 3
}
Is it possible to group the schools and add a count then add it to studentObject? So object could look something like this:
[{school: UCLA, count: 2}, {school: USC, count: 1}]
Using the groupBy operator, you could do something like this:
data$ = this.StudentEnrollment.getRecordsById(list.value.split(/[\r\n]+/));
schoolsGrouped$ = data$.pipe(
// Use concatMap to emit the array elements one by one for the groupBy
concatMap(students => students),
// Group by the student's school
groupBy(student => student.school),
// Merge each grouped set
mergeMap(group =>
zip(of(group.key), group.pipe(toArray())).pipe(
map(([key, students]) => ({ key, students }))
)
),
// Emit one array of the grouped results
toArray()
);
You could then access the data like this:
constructor() {
this.schoolsGrouped$.subscribe(schools =>
schools.forEach(school => console.log(school.key, school.students.length)))
}
There is a working example here: https://stackblitz.com/edit/angular-schools-groupby-deborahk
To add the grouped info to the existing data structure, you can do something like this (see the added tap operator:
schoolsGrouped$ = of(this.data.records).pipe(
// Emit the array elements one by one for the groupBy
concatMap(students => students),
groupBy(student => student.school),
// Merge each grouped set
mergeMap(group =>
zip(of(group.key), group.pipe(toArray())).pipe(
map(([key, students]) => ({ key, students }))
)
),
// Add the result to the existing data object
tap(
school =>
(this.data = {
...this.data,
schools: [
...this.data.schools,
{ school: school.key, count: school.students.length },
],
})
),
// Emit one array of the grouped results
toArray()
);