最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to perform groupBy operation in Angular 2? - Stack Overflow

programmeradmin3浏览0评论

Angular 2 : 2.0.0-alpha.31 / Typescript 1.5

I requested data from a http.get query

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

This query return 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 player grouped by team

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

How can I groupBy team on Angular2 (directly into the @View?) ?

UPDATE

I saw that on Angular 1, this could be done in the view using | groupBy:'propertyName' on ngFor. Is there something like this on Angular 2 ?

Angular 2 : 2.0.0-alpha.31 / Typescript 1.5

I requested data from a http.get query

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

This query return 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 player grouped by team

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

How can I groupBy team on Angular2 (directly into the @View?) ?

UPDATE

I saw that on Angular 1, this could be done in the view using | groupBy:'propertyName' on ngFor. Is there something like this on Angular 2 ?

Share Improve this question edited Feb 20, 2017 at 15:57 HardikDG 6,1223 gold badges28 silver badges55 bronze badges asked Jul 25, 2015 at 6:44 plone1plone1 6761 gold badge10 silver badges15 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

Not sure exactly what version of Angular2 it was introduced but you can call RX's GroupBy function. I don't think you need the .toRx() call in more recent versions either.

Before you subscribe add something like this:

.map((res) => res.json())
.groupBy(
    x => x.team,
    x => x
);

can you use 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)

  1. 暂无评论