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?
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With