0

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.

2
  • Is it a computed property? With your case I think it's best to use computed property Commented Sep 1, 2020 at 21:03
  • Yes this is a computed property Commented Sep 2, 2020 at 4:03

1 Answer 1

3

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.