Vue.js only show objects with a unique property

雨燕双飞 提交于 2019-12-13 03:59:58

问题


I am building a Leaderboard. I have a collection of leaders. There are multiple entries from the same teams. I would like to only show one entry per team (most recent preferably). I am using Firestore for the database.

My html looks like this. (I shortened the code for simplicity)

<div v-for="tracker in trackers" :key="tracker.id">
    <div>{{tracker.team.team_name}}</div>
</div>

If I add this {{ tracker }} to the HTML this is what one tracker splits out

{
  "team": {
    "bio": "<div><!--block-->This is Team One's Bio</div>",
    "fullPath": "avatars/XXXXXX.jpg",
    "team_id": "1",
    "team_name": "Team One",
    "url": "XXXXXXX",
    "id": "XXXXXXX"
  },
  "tracker": {
    "clue": "2",
    "code": "23456",
    "diff": 5269841,
    "team": "1"
  }
}

I have multiple teams. I would like to only show one tracker per "team" so basically group by "teams"

Any help is much appreciated


回答1:


Since you tagged the question computed-properties, you're on the right track. Just create a computed property that limits the trackers to unique teams.

computed: {
    teams() {
        return this.trackers.reduce((teams, tracker) => {
            if (teams.find(team => team.team_id === tracker.team.team_id) === undefined) {
                teams.push(tracker.team);
            }
            return teams;
        }, []);
    }
}

Then use the computed property in your template.

<div v-for="team in teams" :key="team.team_id">
    <div>{{team.team_name}}</div>
</div>

If you need the tracker information associated with the team, create a computed property for unique trackers instead.



来源:https://stackoverflow.com/questions/54488746/vue-js-only-show-objects-with-a-unique-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!