使用Vue JS显示分组的嵌套数组

时间:2018-08-14 15:06:51

标签: javascript arrays vue.js

我正在尝试使用Vue JS对来自ajax调用的团队名称进行分组和显示。

这是原始对象:

0 {  name: Bob Sinclair
 teamname: Francs
 email: bob.sinclair@test.com
 job: Product Manager
 type: Team Member
  }
1 {  name: Neil Jones
 teamname: Dream Team
 email: neil.jones@test.com
 job: Developer
 type: Team Member
  }
2 {  name: Jim Cairns
 teamname: Dream Team
 email: jim.cairns@test.com
 job: Developer
 type: Team Member
  }

我已使用以下功能按“团队名称”对数据进行了分组:

                function groupBy(collection, property) {
                var i = 0, val, index,
                    values = [], result = [];
                for (; i < collection.length; i++) {
                    val = collection[i][property];
                    index = values.indexOf(val);
                    if (index > -1)
                        result[index].push(collection[i]);
                    else {
                        values.push(val);
                        result.push([collection[i]]);
                    }
                }
                return result;
            }

这在控制台中提供了以下输出:

0 { 0 { name: Bob Sinclair
        teamname: Francs
        email: bob.sinclair@test.com
        job: Product Manager
        type: Team Member
      }
1 { 0 { name: Neil Jones
        teamname: Dream Team
        email: neil.jones@test.com
        job: Developer
        type: Team Member
      }
    1 { name: Jim Cairns
        teamname: Dream Team
        email: jim.cairns@test.com
        job: Developer
        type: Team Member
      }

我的问题是使用“ v-for”将其显示。 我希望每个“团队名称”都有一张卡片,下面有一个“名称”列表。

谢谢!

1 个答案:

答案 0 :(得分:1)

假设您将分组数据称为团队:

然后您的模板代码应为:

<div class="team" v-for="team in teams" :key="team[0].teamname">
    <p> {{ team[0].teamname }} </p>
    <div class="teammates" v-for="teammate in team" :key="teammate.name">
        {{ teammate.name }}
        // other infos for teammate
    </div>
</div>