Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 groupby or filter pipe

Tags:

angular

pipe

I am using Angular 2 with symfony 3. I have data array, some datas are same. I want to same datas show just one. I searched pipe and found like this:

import { Pipe, PipeTransform } from "@angular/core";
@Pipe({name: 'groupBy'})
export class GroupByPipe implements PipeTransform {
    transform(value: Array <any> , field: string): Array <any> {
        const groupedObj = value.reduce((prev, cur) => {
            if (!prev[cur[field]]) {
                prev[cur[field]] = [cur]
            } else {
                prev[cur[field]].push(cur);
            }

            return prev;
        }, {});

        return Object.keys(groupedObj).map(key => ({
            key,
            value: groupedObj[key]
        }));
    }
}

When I run my project I am getting this error:

inline template:14:16 caused by: Cannot read property 'reduce' of undefined

How can I solve my problem?

And my template :

<tr *ngFor="let model of data | groupBy:'firstName,lastName'">
   <td>{{ model.user.firstName || '-' }} {{ model.user.lastName || '-' }}</td>
</tr>

Now I can run, but this time I getting firstName undifened error.

How should I call firstName?

like image 295
Mayday Avatar asked Dec 02 '25 15:12

Mayday


1 Answers

If there value is undefined (it could happens when data has not loaded yet or something else) then you should capture the exception.

transform(value: Array <any> , field: string): Array <any> {
    if (value) {
        const groupedObj = value.reduce((prev, cur) => {
            if (!prev[cur[field]]) {
                prev[cur[field]] = [cur]
            } else {
                prev[cur[field]].push(cur);
            }

            return prev;
        }, {});

        return Object.keys(groupedObj).map(key => ({
            key,
            value: groupedObj[key]
        }));
    } else {
        return null;
    }
}
like image 86
Liu Zhang Avatar answered Dec 04 '25 05:12

Liu Zhang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!