如何在Angular 2中执行groupBy操作?

时间:2015-07-25 06:44:33

标签: javascript angular typescript group-by

Angular 2 :2.0.0-alpha.31 / Typescript 1.5

我从http.get查询

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

此查询返回此Json对象(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"}
]

然后我想显示按团队分组的玩家

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

我如何在 Angular2 groupBy team(直接进入@View?)?

更新

我在Angular 1上看到了这个,可以在视图中使用ng | groupBy:'propertyName'来完成。 Angular 2上有这样的东西吗?

2 个答案:

答案 0 :(得分:4)

不确定引入了哪种版本的Angular2,但您可以致电RX's GroupBy function。我认为您不需要在更近的版本中进行.toRx()调用。

在您订阅之前添加以下内容:

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

答案 1 :(得分:0)

你可以使用过滤器吗?

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)