[Vuejs]-How to filter JSON objects of array from multiple attributes in javascript

1👍

You already have the filters in data.filter.options. Use them. You might need to add minLength, maxLength, and some more.

You also have to make sure that the name of these variables in this.filter.options match the variables in your boats, e.g. brand instead of brands.

And I would make the year a range value (min-max) instead of an array. Up to you.

computed: {
  filtered_boats: function () {
    let filtered = this.boats;

    // the minimums
    let mins = {
      "minPrice": 'price',
      "minLength": 'length',
      ...
    };
    filtered = Object.keys(mins).forEach(k => if (this.filter.options[k] !== null) filtered = filtered.filter(boat => boat[mins[k]] >= this.filter.options[k]));

    // the maximums
    let maxs = {
      "maxPrice": 'price',
      "maxLength": 'length',
      ...
    };
    filtered = Object.keys(maxs).forEach(k => if (this.filter.options[k] !== null) filtered = filtered.filter(boat => boat[maxs[k]] <= this.filter.options[k]));

    // the multi-value filters
    let fields = ['brand', 'model', 'type', ...];
    filtered = fields.forEach(f => if (this.filter.options[f].length > 0) filtered = filtered.filter(boat => this.filter.options[f].indexOf(boat[f]) != -1));

    return filtered;
  }
}

Sorry, I couldn’t test the code. But I hope you get the idea!

Leave a comment