Using the v-for loop with Vue, how can I show only one iteration of a repeating value?

Viewed 348

I'm trying to use v-for to loop through an array of objects, with each object containing a key/value pair.

Example: [{rel_date: '1 hour ago', source: 'slack'}, {rel_date: '2 hours ago', source: 'gmail'}, {rel_date: '3 hours ago', source: 'microsoft'}, {rel_date: '4 hours ago', source: 'slack'}]

in my vue template, I'm using v-for loop and a v-if inside the loop to check that (source = 'slack'), but I'm noticing it's rendering this twice since it shows up twice in the array. Is there a way for me to only show the iteration of (source: 'slack') only once?

This is my template code

<div class="col-12 text-left" v-for="last_activity in team_member.activity">
            <span v-if="last_activity.source == 'slack'">
                <span class="label label-slack">[[ last_activity.source ]]</span>
            </span>
        </div>
2 Answers

You need to modify the array on v-for:

<div class="col-12 text-left" v-for="last_activity in [...new Set(team_member.activity.map(JSON.stringify))].map(JSON.parse)">
    <span v-if="last_activity.source == 'slack'">
        <span class="label label-slack">[[ last_activity.source ]]</span>
    </span>
</div>

By the way, it´s better to create a method to filter the array

<div class="col-12 text-left" v-for="last_activity in filterArray(last_activity.source)">
    <span v-if="last_activity.source == 'slack'">
        <span class="label label-slack">[[ last_activity.source ]]</span>
    </span>
</div>

On your methods:

methods:{
  filterArray(array){
    return [...new Set(array.map(JSON.stringify))].map(JSON.parse);
  }
}

If there won't be any other use for the loop, and the only purpose is to check if "slack" exists and show it once, you don't need v-for.

You could do this:

<div v-if="team_member.activity.find(activity => activity.source === 'slack')">
    <span class="label label-slack">slack</span>
</div>
Related