0

I'm newbie to Angular JS.

I am using Angular 2 in my project.

My JSON data is in below

"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"
        }
    ],

I want to display data group by state.

texas   : <div>ASS</div>
florida : <div>ASD</div>
      <div>AAY</div>
      <div>ASD</div>

group.pipe.ts:

@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] 
  }));

}

location.component.ts:

import {GroupByPipe} from '../group.pipe';
@NgModule({
  declarations : [GroupByPipe]
 })

My 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'">

How to solve this?

zgue
  • 3,793
  • 9
  • 34
  • 39
Meg
  • 109
  • 2
  • 2
  • 12

1 Answers1

0

Just Passed the array and field to the below code:

 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] }));
  }

didn't used pipes.

updated my html as like below:

  <div *ngFor="let item1 of pagedItems">

                    <h1>{{item1.key}}</h1> 

                    <div *ngFor="let item of item1.value">
                         // my logic is here.
</div

Meg
  • 109
  • 2
  • 2
  • 12