Implement API filtering using JavaScript

Looking to streamline the data filtering process for a car website where API queries involve parameters like brand, color, price, and fuel.

https://i.sstatic.net/OYUxs.png

The mock API being used is located at

https://api.example.com/api/v1/it/vehicles

Sample query format:

https://api.example.com/api/v1/it/vehicles?filter[transmission]=manual&filter[body]=van,suv

I initiated the process by:

import apiClient from '~/services/VehiclesService';

export default {
  fetchVehicles: async ({ commit }) => {
    const response = await apiClient.get('/vehicles').catch(error => {
      console.log(error);
      return error;
    });
    commit('SET_VEHICLES', response.data.data);
  }
};

implemented in vuejs framework:

<v-list>
 <v-list-item>
   <v-list-item-content>
     <v-list-item-title>
       <v-checkbox class="ma-0 pa-0" v-model="c_v_b_a" :label="`Audi` + ' ' + c_number"></v-checkbox>
       <v-checkbox class="ma-0 pa-0" v-model="c_v_b_b" :label="`Bmw` + ' ' + '(11)'"></v-checkbox>
       <v-checkbox class="ma-0 pa-0" v-model="c_v_b_f" :label="`Fiat` + ' ' + '(13)'"></v-checkbox>
     </v-list-item-title>
    </v-list-item-content>
  </v-list-item>
</v-list>

computed: {
    filterByTerm(brand) {
      if (this.c_v_b_a) {
        this.c_v_b_b = false;
        this.c_v_b_f = false;
        return this.vehicles.filter(car => {
          return car.title.toLowerCase().includes("audi");
        });
      } else if (this.c_v_b_b) {
        this.c_v_b_a = false;
        this.c_v_b_f = false;
        return this.vehicles.filter(car => {
          return car.title.toLowerCase().includes("bmw");
        });
      } else if (this.c_v_b_f) {
        this.c_v_b_b = false;
        this.c_v_b_a = false;
        return this.vehicles.filter(car => {
          return car.title.toLowerCase().includes("fiat");
        });
      } else {
        return this.vehicles;
      }
    }

}

However, this approach doesn't fully align with my goal of efficient data filtering. Are there better ways to implement filtering with API queries?

Any suggestions or tips would be greatly appreciated. Thank you!

Answer №1

I'm uncertain about your specific requirements, but I can refine the car search using the following criteria:

 <input type="checkbox" v-model="brands" value="toyota"/>Toyota
 <input type="checkbox" v-model="brands" value="ford"/>Ford
 <input type="checkbox" v-model="brands" value="honda"/>Honda
 <input type="checkbox" v-model="priceRange" value="15000,25000"/>15,000-25,000
 <input type="checkbox" v-model="priceRange" value="25001,35000"/>25,001-35,000
 <input type="checkbox" v-model="priceRange" value="35001"/>Above 35,000

 data: () => ({
   brands: [],
   vehicles: [
    { title: 'Toyota Corolla', price: 20000},
    { title: 'Ford Fiesta', price: 18000},
    { title: 'Honda Civic', price: 24000},
    { title: 'Toyota Camry', price: 28000},
    { title: 'Ford Mustang', price: 35000},
    { title: 'Honda Accord', price: 30000},
   ]
 }),

 computed: {
  filterCars() {
     return this.vehicles.filter(car => {
       return this.brands.filter(brand => {
        if (car.title.toLowerCase().includes(brand)) {
          return this.priceRange.filter(priceRange => {
            const priceArr = priceRange.split(',')
            const priceStart = priceArr[0]
            const priceEnd = priceArr[1] ? priceArr[1] : Infinity
            return car.price >= parseInt(priceArr[0]) && car.price <= priceEnd
          }).length > 0 || this.priceRange.length === 0
        }
        return false
       }).length > 0
     });
  }
 }

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

Generate a specified quantity of elements using jQuery and an integer

I am working with a json file that contains an items category listing various items through an array. This list of items gets updated every few hours. For example: { "items": [ { "name": "Blueberry", "img": "website.com/blueberry.png" } ...

JavaScript is incorrectly showing the array as empty despite containing strings

I am experiencing an issue with my array of strings in JavaScript. Despite having strings in the array when I print it in the console, the forEach function runs 0 times and JS claims the array is empty when I print its size. What could be causing this?http ...

Exploring Time Scaling and Range Adjustment in D3 Barcharts

My dataset looks something like this: dateRange = [ { date: 2017-03-23, value: 10 }, { date: 2017-03-25, value: 15 }, { date: 2017-04-01, value: 13 }, { date: 2017-04-02, value: 19 } ]; The results can be viewed here: https://embed.plnkr.co/iOBAuCZmo ...

Is my Bootstrap malfunctioning? The grid system seems to be malfunctioning

My very first question here is quite simple. I have a script that creates rows with dynamic content by appending 4 boxes (columns) in one row and then appending the row to the container. After completing this process, it appends the container to the main c ...

Having trouble getting my local website to load the CSS stylesheet through Express and Node.js in my browser

https://i.stack.imgur.com/qpsQI.png https://i.stack.imgur.com/l3wAJ.png Here is the app.js screenshot: https://i.stack.imgur.com/l3wAJ.png I have experimented with different combinations of href and express.static(""); addresses. However, I am ...

Experimenting with ngModel in a Jasmine test suite

I've created a directive that generates input fields and connects them to the scope using ngModel. When a user uses this directive in the HTML file like so: <div tk-quick-form="formStructure" form-data="formData" id="main_form" ></div> a ...

Tips for effectively managing a Vue3/Quasar project that involves both dynamic and static image paths

I encounter an issue that seems rather common. Sometimes in my quasar application, I utilize the vite/quasar shortcut for assets like the example below: <q-carousel-slide :name="2" class="column no-wrap flex-center q-pa-none"> & ...

Guide to crafting a javascript variable from MySQL through the power of PHP and AJAX

I am not very experienced in working with AJAX and javascript. I am currently trying to pass longitude and latitude values from a MySQL database to javascript, but it doesn't seem to be working as expected. Can anyone help me figure out what I might b ...

Is there a way to trigger a modal popup when hovering over a Bootstrap 5 card?

After coming across a handy template online, I decided to implement a modal pop-up feature when hovering over cards using Bootstrap 5. Here's what I have so far: class SavedEpisodes extends Component { $(function() { $('[data-toggle=&qu ...

Customizing CSS according to specific URLs

I have two different domains - one ending with .nl and the other ending with .be. For instance, domain.nl and domain.be. Both domains share a similar overall style, but I want certain elements to have distinct styling depending on whether it is the .nl o ...

"Enhance Your Communication: Utilize setTimeout in Ajax

Hey there, I could really use some help with the setTimeout function in my code. No matter what I try, it just doesn't seem to work. I'm currently working on a chat system where I need to send and receive messages (testing by opening 2 browser ...

Integrating Vue.js code into Laravel's Blade templates for enhanced functionality

I'm having trouble accessing data from a Vue component function in a Laravel blade template that includes the component. When I use this code, the page just loads as a blank page. However, if I remove the @ symbol from the blade span, the autocomplete ...

Using a Javascript library within an Angular component: A comprehensive guide

I've been working on a Web-Client project that involves visualizing sensor data such as velocity and acceleration within a coordinate system. In order to display this coordinate system, I decided to use the graph.js library from https://github.com/dhu ...

What is the best way to deploy a Vue Webpack application using Sails.js?

I am currently managing a Sails.js server alongside a Vue Webpack application, running as separate entities. Here's how my folder structure is laid out: /application-root/server/ /application-root/client/ Within the /server/ directory lies my Sails ...

What's the most effective approach to verify if all visible input fields possess a value? (excluding the use of jQuery validator

In order to ensure that all necessary fields are selected, I need to implement a check upon clicking a button. Below is the HTML code: <input type="text" class="required-entry"> <input type="text" class="required-entry"> <input type="text" ...

Accessing component variables within an event in Angular 2 (dealing with scope problems)

I am currently facing an issue with scoping in my component click event. Specifically, I need to access private variables within the component, but the keyword this now refers to the event scope rather than the component's. This has led to an error wh ...

Storing the information filled out in the form and utilizing it to navigate to the correct destination URL

With the generous assistance and insightful advice from members of Stack Overflow, I am nearing completion of my quiz project. However, I do have a few lingering questions regarding some final touches needed for the project. Before delving into those quest ...

exceeding the maximum call stack limit when repeatedly calling a function with parameters in jQuery

I have been attempting to create a blinking icon using the following HTML code: <button type="button" id="user-card-icon-headphones" class="user-card__button" disabled="" > <i class="fa fa-headphones"></i> </button> <button t ...

Continuously make Ajax requests to populate numerous div elements

There are two div elements present on my webpage. <div id="1"></div> <div id="2"></div> I am attempting to dynamically populate these divs using the following php call. <script> var queries = ["SELECT * from table1", "S ...

Is Dealing with Multiple AJAX Requests a Pain?

Currently, I am utilizing AJAX to retrieve a list of active streams from TwitchTV along with their viewers, updating every second. Sometimes the stream list can become quite long, so my plan is to divide the AJAX requests into 2 or 3 parts: 1) Obtain Numb ...