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

时间:2019-01-07 13:03:59

标签: vue.js vuejs2 v-for

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'}

3 个答案:

答案 0 :(得分:2)

您可以使用Set

  

通过Set对象,您可以存储任何类型的唯一值,无论是原始值还是对象引用。

MDN的示例:

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

只需根据您的需要进行修改即可。

答案 1 :(得分:1)

使用reduce对数组的每个项目执行 reducer 函数,然后使用assign将单个匹配项合并到现有对象中。合并过程需要删除(或实际替换)重复项。

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>

答案 2 :(得分:0)

您可以使用计算来显示按日期排序的所有问题的数组。