0

所以这是我的 JSON 数据;

    {
        "team_name": "New Team!",
        "user_name": "hey_user",
        "games": []
    },
    {
        "team_name": "New Team!",
        "user_name": "testing_user",
        "games": []
    },
    {
        "team_name": "Another Cool Team!",
        "user_name": "test_user_2",
        "games": []
    }

我将此添加到我的 .eco 模板中:

 <% for person in @persons: %>
    <%= person.team_name %>    
    <%= person.user_name %> <br /> <br />
 <% end %>

哪个输出:

New Team! hey_user
New Team! testing_user

但我希望它输出:

  New Team! hey_user, testing_user, etc.

因此,如果有意义的话,团队名称不会一直出现在每个新用户身上。实现这一目标的最佳方法?

4

1 回答 1

0

If I understand correctly you want to group users by teams. You can use underscore's groupBy method

var groups = _.groupBy(json, 'team');

It will give you something like that:

{
    "New Team!": [
        {
            "team_name": "New Team!",
            "user_name": "hey_user",
            "games": []
        },
        {
            "team_name": "New Team!",
            "user_name": "testing_user",
            "games": []
        }
    ],
    "Another Cool Team!": [
        ...
    ]
}

Then you can pass this to template, iterate over it and print team and then iterate through inner array of users. If you need array instead of hash, you can run pairs over it.

于 2015-10-05T21:25:57.457 回答