Vuejs - How to get all unique values in a array (remove duplicates) using v-for

*爱你&永不变心* 提交于 2019-12-24 08:37:06

问题


How to show only one button per every distinct date ?

can i use two v-for loops ? how to select distinct values in my loop?

<div v-for="question in allQuestions" >
  <button v-for="date in question.date">
    {{date}}
  </button>
</div>

Data model :

allQuestions : []
question : {'id' : '123' , 'date' : '25'}

回答1:


You can use Set:

The Set object lets you store unique values of any type, whether primitive values or object references.

MDN's example:

const numbers = [2, 3, 4, 4, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 5, 32, 3, 4, 5]

console.log([...new Set(numbers)])

Just modify it to your needs.




回答2:


Use reduce to execute a reducer function on each item of the array, then merge the individual matches into the existing object with assign. This merging process takes care of removing (or actually replacing) duplicate items.

const vm = new Vue({
  el: '#app',

  data() {
    return {
      allQuestions: [
        { id: '123', date: '14' },
        { id: '456', date: '2' },
        { id: '933', date: '2' },
        { id: '789', date: '7' },
        { id: '220', date: '14' }
      ]}
  },

  computed: {
    uniqueQuestions() {
      return this.allQuestions.reduce((seed, current) => {
        return Object.assign(seed, {
          [current.date]: current
        });
      }, {});
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div v-for="question in uniqueQuestions" :key="question.date">
    <button v-for="date in question.date">
    {{date}}
  </button>
  </div>
</div>



回答3:


You can use computed to display an array of all your questions sorted by date.



来源:https://stackoverflow.com/questions/54074976/vuejs-how-to-get-all-unique-values-in-a-array-remove-duplicates-using-v-for

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