Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

<li v-for="product in products">
{{product.category}}
</li>

Array:

products: [
      { id: '1', title: 'Test 1', category: 'Test 3' },
      { id: '2', title: 'Test 2', category: 'Test 1' },
      { id: '3', title: 'Test 3', category: 'Test 2' },
      { id: '3', title: 'Test 4', category: 'Test 1' },
      { id: '5', title: 'Test 5', category: 'Test 3' }
    ]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
958 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

<li v-for="category in productCategories">
  {{category}}
</li>

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...