A
A
Anton2017-09-21 18:53:48
Vue.js
Anton, 2017-09-21 18:53:48

How to filter a list by multiple parameters?

It is necessary to filter the list by two parameters, there are no problems with one.
In this case, it will filter by itemData , but how to make it possible to filter by monthData as well ?

filteredItems() {
        return this.response.filter(item => {
          var itemData = item.location_name.indexOf(this.active_location) > -1
          var monthData = item.month.indexOf(this.active_date) > -1
          return itemData
        })
      }

Filtering reference with one parameter:
Example

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2017-09-21
@Ooos

If matches must be on both: return itemData && monthData.
If one is enough: return itemData || monthData.
UPD. In general, let's try to implement a more general solution, with an arbitrary number of filters.
Let's add filter descriptions. Let this be an object whose property names match the properties being filtered, and whose values ​​are objects containing the current filter value and a comparison function:

data: {
  filters: {
    'какое-то свойство': {
      value: какое-то дефолтное значение,
      compare: (itemValue, filterValue) => сравнение значений фильтра и элемента фильтруемого массива
    },
    ...
  },
  ...

Let's create controls so that the user can edit the filter values, for example: or Let's make a calculated property that represents the filtered data. We go through the filters, at each iteration we discard those elements that do not pass the current filter:
<input v-model="filters.xxx.value">
<select v-model="filters.yyy.value">
computed: {
  filteredItems() {
    return Object.entries(this.filters).reduce((items, [ key, filter ]) => {
      return items.filter(item => filter.compare(item[key], filter.value));
    }, this.items);
  },
  ...

jsfiddle.net/qwsn9dt7

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question