So the requirement is like: I got a array of objects (e.g. Array)
[
{ empDept: 'Engineering', empLoc: 'Pune', empName: 'John' },
{ empDept: 'Engineering', empLoc: 'Mumbai', empName: 'Harry' },
{ empDept: 'HR', empLoc: 'Pune', empName: 'Denis' },
{ empDept: 'Finance', empLoc: 'Mumbai', empName: 'Elvis' },
]
I will have a function which will accept the name of the property as a parameter, on which the employee list will be grouped. So if the input parameter value is 'empDept', then I want the result as below:
[
{
key: 'Engineering',
values: [
{ empDept: 'Engineering', empLoc: 'Pune', empName: 'John' },
{ empDept: 'Engineering', empLoc: 'Mumbai', empName: 'Harry' },
]
},
{
key: 'HR',
values: [
{ empDept: 'HR', empLoc: 'Pune', empName: 'Denis' },
]
},
{
key: 'Finance',
values: [
{ empDept: 'Finance', empLoc: 'Mumbai', empName: 'Elvis' },
]
}
]
I'm using the RxJs groupBy operator to achieve this. I have tried the below code, but it doesn't seem to give the desired result:
this.groupedEmployees$ = employees$.pipe(
groupBy(person => person.empDept),
mergeMap(group => of({ key: group.key, values: group.pipe(mergeMap(x => toArray())) })),
);
Appreciate your help.