Angular 2 groups or filter channel

I am using Angular 2 with symfony 3. I have data array

, some data is the same. I want the same data to show only one. I searched pipe

and found the following:

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 get 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 get firstName undifened

.

How do I call firstName

?

+3


source to share


1 answer


If the value is equal undefined

(this can happen when the data hasn't been loaded yet or whatever), you should catch 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;
    }
}

      

+2


source







All Articles