xew
xew

Reputation: 47

Vue.js - Filter multiple fields

I'm trying to filter a on a nested array inside an array of objects in an Vue.js. Here's a snippet of the component code:

filteredProducts: function() {
  if (!this.filters.appointments.length && !this.filters.powers.length && !this.filters.materials.length && !this.filters.lamps.length) return this.products;
  return this.products.filter(product => {
    return product.filter(p => {
      let filteredAppointments = this.filters.appointments ? _.difference(this.filters.appointments, p.appointment.split(',')).length === 0 : true,
        filteredPowers = this.filters.powers ? this.filters.powers.includes(p.total_power_lamps) : true,
        filteredMaterials = this.filters.materials ? this.filters.materials.includes(p.material) : true,
        filteredLamps = this.filters.lamps ? this.filters.lamps.includes(p.count_lamps) : true,
        filteredPrice = p.price >= this.rangePrice[0] && p.price <= this.rangePrice[1];
      return filteredAppointments && filteredPowers && filteredMaterials && filteredLamps && filteredPrice;
    }).length > 0;
  });
}

How do I display only the filters that are used ? For example, if only one filter is selected, then no other filters are needed. Also, if several are selected, it should filter by both.

Upvotes: 0

Views: 728

Answers (1)

Babacar C. DIA
Babacar C. DIA

Reputation: 420

I think this is what you're looking for

filteredProducts () {
  let results = this.products
  if(this.filters.appointments.length) {
    results = results.filter(logicFilterHere)
  }
  if(this.filters.powers.length) {
    results = results.filter(logicFilterHere)
  }
  if(this.filters.materials.length) {
    results = results.filter(logicFilterHere)
  }
  return results
}

Upvotes: 3

Related Questions