What is the most effective way to use checkboxes to apply multiple filters to an array of objects?

Let me simplify the description.

Within the App component, I fetch data from a JSON file and store it in the flightsList array.

My goal is to filter this array based on checkboxes selected in the FlightOptions and Airlines components.

The issue that I'm facing is figuring out how to apply multiple filters simultaneously.

<template>
     <div id="app">
      <div class="filters">
        <FlightOptions @clicked="onCheckboxClick" />
        <Airlines v-bind:airlinesList="airlinesList" />
     </div>
     <div class="flightsList">
       <FlightsList v-bind:flightsList="filteredFlightsList" />
     </div>
    </div>
  </template>

export default {
  name: "App",
  components: {
    FlightOptions,
    Airlines,
    FlightsList,
  },
  data() {
    return {
      flightsList: [],
      airlinesList: {},
      optionsFilters: [],
    };
  },
  mounted() {
    this.getFlightsList();
  },
  methods: {
    onCheckboxClick(value) {
      this.optionsFilters = value;
      console.log(value);
    },
    getFlightsList() {
      fetch("results.json")
        .then((res) => res.json())
        .then((data) => {
          this.airlinesList = data.airlines;
          this.flightsList = data.flights;
        })
        .catch((err) => console.error("Error", err));
    },
  },
  computed: {

     // I have experimented with different filtering approaches, but struggling with multiple conditions

 }
   
};

----------- FlightOptions -------------

<template>
  <div class="options">
    <p class="options__title">Опции тарифа</p>
    <div class="options__checkbox">
      <input v-model="optionsFilters" value="onlyDirect" type="checkbox" id="onlyDirect" />
      <label for="onlyDirect">Только прямые</label>
    </div>
    <div class="options__checkbox">
      <input v-model="optionsFilters" value="withBaggage" type="checkbox" id="withBaggage" />
      <label for="withBaggage">Только с багажом</label>
    </div>
    <div class="options__checkbox">
      <input v-model="optionsFilters" value="onlyReturn" type="checkbox" id="onlyReturn" />
      <label for="onlyReturn">Только возвратные</label>
    </div>
  </div>
</template> 

<script>
export default {
  data() {
    return {
      optionsFilters: []
    }
  },
  watch: {
    optionsFilters: function() {
      this.$emit('clicked', this.optionsFilters)
    }  
  }
}
</script>

Answer №1

Here's a helpful suggestion:

computed: {
  filteredFlightsList() {
    if (!optionsFilters.length) return this.flightsList;
    return this.flightsList.filter((item) => {
      return this.optionsFilters.every((option) => item[option]); 
    });
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered: DOMException - Prevented a frame originating from "domain_name" from accessing a different origin frame

Utilizing the Mautic newsletter for my website has been a great experience. Here is the js code I've been using: /** This section should only be included once per page if manually copying **/ if (typeof MauticSDKLoaded == 'undefined') { ...

I am looking for JavaScript or jQuery code that allows me to incorporate a "Save This Page As" button

Is there a way to enhance the saving process for users visiting an HTML page, rather than requiring them to go through File > Save As? I am interested in implementing a "Save Page As" button on the page that would trigger the save as dialog when clicke ...

Configuring Google Maps API (including charts) for maximum height of 100%

I am having trouble getting my map to display at 100% height using the Google Maps API. I've encountered similar issues in the past with the Google Charts API as well. From what I've gathered, it seems like setting the height of the html and bod ...

Inquiring about the intricacies of using Regular Expressions in

Can anyone provide a regex that only allows the characters 0-9, a-z, A-Z, hyphen, question mark, and "/" slash, with a character length between 5 to 15? I attempted the following approach, but it did not yield the desired result: var reg3 = /^([a-zA-Z0-9? ...

The loading of content will happen only after the fadeOut effect

I'm attempting to incorporate content loading between fadeOut and fadeIn. When I execute the code below, the content loads before the fadeOut is complete: $("#contentArea").fadeOut(1000); $("#contentArea").promise().done(); $("#contentArea").load(c ...

A Node.js feature that enables atomic file replacement, triggering watchers only once

I have a unique scenario where I need to handle two types of processes. One process is responsible for writing a file, while the other processes are required to read it whenever there is a change. In my research, I came across fs.watch as a solution to ke ...

IE11 blocking .click() function with access denied message

When attempting to trigger an auto click on the URL by invoking a .click() on an anchor tag, everything works as expected in most browsers except for Internet Explorer v11. Any assistance would be greatly appreciated. var strContent = "a,b,c\n1,2,3& ...

State in Vuex is failing to update effectively when actions are being utilized

I'm trying to wrap my head around VueX, but I'm having trouble getting Axios to work with it. In my store.js file, I have the following setup: state: { cards: [], currentPage: 1, lastPage: 2, }, actions: { loadGradients(page ...

Laravel 8 not passing CSRF token to Vue.js

I am attempting to create a file uploader using vuejs within laravel 8. To achieve this, I have included the following meta tag: <meta name="csrf-token" content="{{ csrf_token() }}"> However, I continue to encounter error 419. Be ...

I'm having trouble understanding why I can't access the properties of a class within a function that has been passed to an Angular

Currently, I have integrated HTML 5 geolocation into an Angular component: ... export class AngularComponent { ... constructor(private db: DatabaseService) {} // this function is linked to an HTML button logCoords(message, ...

Embed a YouTube video within the product image gallery

Having trouble incorporating a YouTube video into my Product Image Gallery. Currently, the main product photo is a large image with thumbnails that change it. You can see an example on my website here. Whenever I attempt to add a video using the code below ...

Angular Functions and Their Application

Just starting out with Angular and facing a challenge with handling downloaded JSON data. I wrote this function: for (var i = 0; i < $scope.Objects.length; i++){ $http.get($scope.Objects[i]["Commit"]).success(function(data) { Commit = data ...

The Postman post request is successful, however when using Axios to make the same request to the URL, a

I am currently using a Rails backend in combination with a Vue frontend. When I make a request to http://localhost:3000/login and include the following request body: {"user": { "email": "<a href="/cdn-cgi/l/email- ...

Resolve the route expression before the API request is fully processed

As a hobby coder, I have some gaps in my knowledge and despite trying various solutions, I have not been able to solve this issue. Idea Outcome My goal is to call my Express server, retrieve data from an external API, and render the data once it's f ...

Create a dynamic feature in Bootstrap4 where the navigation bar changes color as the user scrolls to different sections of the

Currently building my personal portfolio website with Bootstrap 4, I came up with a great idea: changing the navigation bar color based on different sections of the website. I attempted to achieve this using JQuery's offset and scrollTop functions, bu ...

Is there a way to display a browserAction popup from within a pageAction popup?

My Project's Background I am currently working on developing a web extension that allows users to tag bookmarks and easily navigate to them based on those tags. Originally, I intended to access the native tags feature, but due to limitations in the w ...

What are some methods for resolving the problem of CORS policy blocking access to retrieve data from Yahoo Finance?

Currently, I am attempting to retrieve the price of a stock within my pure React App by utilizing fetch. When I try to fetch without any options or configurations, using fetch(url), I encounter the following error: Access to fetch at 'https://quer ...

Utilizing JSON Data with JQuery: A Beginner's Guide

I am using a setTimeout function to reload another function every 5 seconds. The update_list function is responsible for rendering entrances in a view. However, when there are many entrances and you have scrolled down, the list empties and reloads every e ...

Most efficient method for comparing two JSON arrays and rearranging their positions

I am faced with a challenge involving two Javascript JSON arrays. The arrays in question are named this.BicyclePartsOLD and this.BicyclePartsNEW. Both arrays contain an attribute named "ListOrder". The OLD array is currently ordered from ListOrder 1 to n ...

Guide on how to retrieve a server-generated message within a jQuery script on an EJS page

Is there a way to retrieve and utilize a variable passed from a controller to an EJS page in a jQuery script? Below is the code snippet for reference: app.get('/form', (req, res) => { res.render('form', { errorMessage: & ...