Remove repeated elements from v-for in VueJS

后端 未结 2 1731
别跟我提以往
别跟我提以往 2020-12-21 10:53

I\'m using the following code to display categories from an array. The array may contain duplicate categories. Is there any way I can only select unique elements in VueJS?

2条回答
  •  眼角桃花
    2020-12-21 11:36

    You can create a computed property with the unique values you want. If you include Lodash in your project, try _.uniq

    import uniq from 'lodash/uniq'
    // ...snip
    
    computed: {
      productCategories () {
        return uniq(this.products.map(({ category }) => category))
      }
    }
    

    and in your template

  • {{category}}

  • If you're not keen on introducing Lodash (or other utility libraries), the same can be achieved with a Set

    productCategories () {
      return [...new Set(this.products.map(({ category }) => category))]
    }
    

    Note: I've converted the Set to an array as Vue.js doesn't seem able to iterate the Set (or any other Iterator).

提交回复
热议问题