1

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:

computed: {
          filteredProducts: function () { // https://codepen.io/arhey/pen/QrbxdX
            return this.products.map(product => {
                return product.filter(p => {
                    return this.powers.includes(p.total_power_lamps);
                });
            });
        }
    },

As a result, the data is filtered but not updated on the page.

filteredProducts: Array[6]
0: Array[2] <- Filtered!
1: Array[2] <- Filtered!
2: Array[0] <- Remove?
3: Array[0] <- Remove?
4: Array[0] <- Remove?
5: Array[0] <- Remove?

Can't update data on the page due to empty arrays.

How do I delete empty arrays ?

1
  • Have you tried skipping the empty ones in the component with a v-if="product!=null" ? Commented Aug 31, 2020 at 15:50

1 Answer 1

2

The map function returns an array with same length as the original one, i recommend to use filter instead of map to return only the filled arrays :

computed: {
          filteredProducts: function () { 
            return this.products.filter(product => {
                return product.filter(p => {
                    return this.powers.includes(p.total_power_lamps);
                }).length>0;//return only filled arrays
            });
        }
    },
Sign up to request clarification or add additional context in comments.

1 Comment

How do I filter multiple fields ? If one filter was selected, "OR" was triggered, if two or more filters were selected "AND". return this.powers.includes(p.total_power_lamps) && this.materials.includes(p.material) && this.lamps.includes(p.count_lamps)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.