How to display associated JSON data together in a backbone.js .eco template

34 Views Asked by At

So here is my JSON data;

    {
        "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": []
    }

I'm adding this to my .eco template:

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

Which outputs this:

New Team! hey_user
New Team! testing_user

But I want it to output:

  New Team! hey_user, testing_user, etc.

So the Team Name doesn't keep appearing for each new user, if that makes sense. Best way to accomplish this?

1

There are 1 best solutions below

0
antejan On

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.