source

Vuejs - v-for를 사용하여 어레이의 모든 고유 값을 가져오는 방법(중복 제거)

goodcode 2022. 8. 8. 20:04
반응형

Vuejs - v-for를 사용하여 어레이의 모든 고유 값을 가져오는 방법(중복 제거)

구별되는 버튼당 하나의 버튼만 표시하는 방법 date?

두 개의 v-for 루프를 사용할 수 있습니까? 루프에서 고유한 값을 선택하는 방법은 무엇입니까?

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

데이터 모델:

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

Set을 사용할 수 있습니다.

Setobject를 사용하면 원시 값이나 객체 참조 등 모든 유형의 고유한 값을 저장할 수 있습니다.

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를 사용하여 배열의 각 항목에 대해 축소 함수를 실행한 다음 할당을 사용하여 개별 일치 항목을 기존 개체에 병합합니다.이 병합 프로세스에서는 중복 항목을 제거(또는 실제로 교체)합니다.

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>

computed를 사용하면 날짜별로 정렬된 모든 질문을 표시할 수 있습니다.

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

반응형