Home > database >  Remove duplicate list item in v-for
Remove duplicate list item in v-for

Time:07-24

I'm retrieving all groups from an axios request at the page load and I store that data inside an empty array inside a reactive object like this,

const groupHandler = reactive({
    groups: [],
});

And when the user clicked one of his product and click on edit a form will appear like this,

enter image description here

Here you can see Group 1 has been repeated. And there is another reactive object to store that user's product's group id,

const productForm = reactive({
   group: 2,
});

So when the user clicks on a product productForm.group will be filled with that product's group id. I want to prevent this been duplicated in my edit product form. I'm using the v-for directive to loop the groups array,

<li
    v-for="group in groupHandler.groups"
    :key="group.id"
    :group-id="group.id" >
      {{ group.name }}
</li>

So how to prevent this duplicate? In the v-for directive, I could use a condition like if group.id is not equal to productForm.group print group.name But I have no clue to do this. Really appreciate if somebody could help thanks.

CodePudding user response:

You can use v-for in the template element, and then in the li element, you can use v-if condition to only render the group which doesn't have that id

<template v-for="group in groupHandler.groups">
<li
    v-if="group.id !== productForm.group"
    :key="group.id"
    :group-id="group.id" >
      {{ group.name }}
</li>
</template>

CodePudding user response:

You can simply achieve this by using Array.filter() method in the v-for directive itself.

v-for="group in groupHandler.groups.filter(({ name }) => !uniqPropValue[name] && (uniqPropValue[name] = true))"

Live Demo :

new Vue({
  el: '#app',
  data: {
    uniqPropValue: {},
    groupHandler: {
        groups: [{
        id: 1,
        name: 'Group 1'
      }, {
        id: 2,
        name: 'Group 1'
      }, {
        id: 3,
        name: 'Group 2'
      }, {
        id: 4,
        name: 'Group 3'
      }]
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <li
      v-for="group in groupHandler.groups.filter(({ name }) => !uniqPropValue[name] && (uniqPropValue[name] = true))"
      :key="group.id"
      :group-id="group.id">
    {{ group.name }}
  </li>
</div>

  • Related