As a newcomer to Angular JS, I have recently started using Angular 2 for a project of mine.
Here is an example of my JSON data:
"locations": [
{
"id": "ASS",
"name": "test center",
"city": "Staten Island",
"zip": "10301",
"state" : "texas"
},
{
"id": "ASD",
"name": "test center1",
"city": "Staten Island",
"zip": "10301",
"state" : "Florida"
},
{
"id": "AAY",
"name": "test center2",
"city": "Staten Island",
"zip": "10301",
"state" : "Florida"
},
{
{
"id": "ASD",
"name": "test center1",
"city": "Staten Island",
"zip": "10301",
"state" : "Florida"
}
],
The goal is to display the data grouped by state:
texas : <div>ASS</div>
florida : <div>ASD</div>
<div>AAY</div>
<div>ASD</div>
In the 'group.pipe.ts' file:
@Pipe({name: 'groupBy'})
export class GroupByPipe implements PipeTransform {
transform(value: Array<any>, field: string): Array<any> {
console.log('test');
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]
}));
}
And in the 'location.component.ts' file:
import {GroupByPipe} from '../group.pipe';
@NgModule({
declarations : [GroupByPipe]
})
However, I encountered an error:
Unhandled Promise rejection: Template parse errors:
The pipe 'groupBy' could not be found (" <div class="col-sm-12 left_otr">
<div class="col-md-6 col-sm-6 left" *ngFor="let [ERROR ->]item
of pagedItems | groupBy : 'state'">
Any suggestions on how to resolve this issue?