Vuejs - 如何使用 v-for 获取数组中的所有唯一值(删除重复项)

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

如何每个 distinct date 只显示一个按钮?

我可以使用两个 v-for 循环吗?如何在我的循环中 select distinct 值?

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

数据模型:

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

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

您可以使用 Set:

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

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

根据需要修改即可。

使用reduce to execute a reducer function on each item of the array, then merge the individual matches into the existing object with 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>