How to perform groupBy operation in Angular 2?

Angular 2 : 2.0.0-alpha.31 / Typescript 1.5

I requested data from http.get request

 this.http.get('/data/players.json') .toRx() .map((res) => res.json()) .subscribe((data) => { this.players = data; }); 

This request returns me this Json object ( this.players )

 [ {"team":"teamA","name":"player1","age":"1"}, {"team":"teamA","name":"player2","age":"1"}, {"team":"teamA","name":"player3","age":"1"}, {"team":"teamB","name":"player4","age":"1"}, {"team":"teamB","name":"player5","age":"1"} ] 

Then I would like to display a player grouped by team

 teamA: player1,player2,player3 teamB: player4,player5 

How can I groupBy team on Angular2 (right in @View?)?

UPDATE

I saw that in Angular 1 this can be done in a view using | groupBy:'propertyName' | groupBy:'propertyName' on ngFor. Is there something similar on Angular 2?

+8
javascript angular group-by typescript
source share
2 answers

I don’t know which version of Angular2 was introduced, but you can call the RX GroupBy function . I don't think you need a call to .toRx() in later versions.

Before subscribing, add something like this:

 .map((res) => res.json()) .groupBy( x => x.team, x => x ); 
+4
source share

Can I use a filter?

 var test = [ {"team":"teamA","name":"player1","age":"1"}, {"team":"teamA","name":"player2","age":"1"}, {"team":"teamA","name":"player3","age":"1"}, {"team":"teamB","name":"player4","age":"1"}, {"team":"teamB","name":"player5","age":"1"} ]; function FilterByTeam(obj){ console.log(obj); return obj.team === "teamA"; } var teamA = test.filter(FilterByTeam); console.log(teamA) 
0
source share

All Articles