D
D
danilr2019-06-29 08:39:15
JavaScript
danilr, 2019-06-29 08:39:15

How to filter by directory?

I make a catalog + filters for it on Vue.
There are two arrays at the input - one is all information for the elements of the catalog.
The second one is filters for the directory.
You need to filter by the keys cow, pig, bird, ram ...
These are the arrays

export const meatFood = [
  {
    title: 'Говядина тушеная',
    cow: true,
    pig: false,
    bird: false,
    ram: false,
    deer: false,
    kasha: false,
    others: false
  },
    title: 'Тушеная',
    cow: false,
    pig: false,
    bird: false,
    ram: true,
    deer: false,
    kasha: false,
    others: false
  },
    title: 'Вареная',
    cow: true,
    pig: false,
    bird: false,
    ram: true,
    deer: false,
    kasha: false,
    others: false
  },
]
// фильтры
      filters:[
        {
          name: 'Говядина',
          code: 'cow',
          img: '/img/filters/cow.svg'
        },
        {
          name: 'Свинина',
          code: 'pig',
          img: '/img/filters/pig.svg'
        },
        {
          name: 'Птица',
          code: 'bird',
          img: '/img/filters/bird.svg'
        },
        {
          name: 'Баранина',
          code: 'ram',
          img: '/img/filters/ram.svg'
        },
        {
          name: 'Оленина',
          code: 'deer',
          img: '/img/filters/deer.svg'
        },
        {
          name: 'Каши',
          code: 'kasha',
          img: '/img/filters/kasha.svg'
        },
        {
          name: 'Остальное',
          code: 'others',
          img: '/img/filters/others.svg'
        },
      ]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-06-29
@danilr

Based on the filters array, create controls to toggle filter activity:

<label v-for="f in filters">
  <input type="checkbox" v-model="f.checked">
  {{ f.name }}
</label>

And make a computed property that will represent the filtered products:
computed: {
  filteredFood() {
    const filters = this.filters.filter(n => n.checked).map(n => n.code);
    return this.meatFood.filter(n => filters.some(f => n[f]));
  },
},

UPD. The data structure is certainly strange - why separate boolean properties for the composition of the product is not very clear. Why not one property, an array, where this very composition will be simply listed?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question