Strategies for reducing the need for multiple if/else statements when filtering result sets

Currently, my webpage has a left and right section. The right section displays results based on the filters chosen by the user on the left. Upon selecting filters and clicking a button, a query is sent to the server to retrieve the relevant results.

I've started noticing that my if/else statements are becoming quite messy, particularly when adding new filters. Is there a more efficient way to handle this?

The current filters in use are:

foo, bar, fromdate, todate, profile

Here is an example of my if/else structure:

var query = "?"
if (self.foo === '' && self.bar === '' && self.fromdate === '' && self.todate === '' && self.profile === '')
   query = "";
else if (self.foo.length > 2 && self.bar === '' && self.fromdate === '' && self.todate === '' && self.profile === '')
   query += "foo=" + self.foo;
else if (self.foo.length > 2 && self.bar.length > 2 && self.fromdate === '' && self.todate === '' && self.profile === '')
   query += "foo=" + self.foo + "&bar=" + self.bar;

// ...

xhr.open('GET', apiURL+query)
self.loading = true
xhr.onload = function () {
    self.requests = JSON.parse(xhr.responseText)
    //do stuff
    self.loading = false;
}

Question Is there a better approach to simplify and manage these if/else conditions?

Answer №1

Here is my suggestion


    let filterParams = [
       'apple',
       'banana',
       'orange',
       etc...
    ]
    let filter = '';
    filterParams 
       .forEach(item => filter = this[item].length > 2 ? 
           filter + `&${item}=${this[item]}` : filter );
    filter = filter.length ? '?' + filter : filter;

If you need to add a new item, simply update the filterParams array without altering the logic.

Answer №2

I plan to approach this task in the following manner:

var query = '?';
query += self.foo.length > 2 ? '&foo=' + self.foo : '';
query += self.bar.length > 2 ? '&bar=' + self.bar : '';
query += self.fromdate ? '&fromdate=' + self.fromdate : '';
query += self.todate ? '&todate=' + self.todate : '';
query += self.profile ? '&profile=' + self.profile : '';

Additionally, when dealing with an object like:

var self = {
  foo: "hello",
  bar: "w",
  profile: "me"
}

You can expect the resulting query to be ?&foo=hello&profile=me. The presence of ?& at the start does not impact the request, so there is no need to eliminate the leading &.

Answer №3

Perhaps this illustration will spark your imagination. I trust it offers a straightforward, clear, and adaptable solution - regardless of how many inputs are linked to the params model in the HTML template, the JavaScript code remains unchanged.

new Vue({
  el: '#app',
  data: {
    params: {}
  },
  computed: {
    query () {
      var query = []
      for (param in this.params)
        if (this.params[param].length > 2)
          query.push(param + '=' + this.params[param])
      query.length
        ? query = '?' + query.toString().replace(/,/g, '&')
        : query = ''
      return query
    }
  },
  methods: {
    submit () {
      console.log('my.url' + this.query)
    }
  }
})
<div id="app">
  <input type="text" v-model="params.foo">
  <input type="text" v-model="params.bar">
  <input type="text" v-model="params.baz">
  <button @click="submit">Submit</button>
</div>

<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aed8dbcbee9c809b809d">[email protected]</a>/dist/vue.min.js"></script>

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

Comparing AngularJS $interpolate with $filter

AngularJS offers different tools for manipulating data displayed to users. While $filter is commonly used for formatting data, $interpolate enables real-time updates within a text string. Do $interpolate and $filter have any connection? How do they differ ...

Arranging elements based on specific coordinates

const renderTimeSlots = () => { const timeSlots = []; for (let i = parseInt(workStartsAt); i <= parseInt(workEndsAt); i++) { if (i !== 0) { timeSlots.push( <div className="flex flex-row cursor-pointer"> ...

The back-to-top button guides users back to their last visited page

I'm excited to explore AngularJS and I want to add two "return to top" buttons on different pages. Here's what I have so far: Page 1: <h1 id = "top"> .......... <a href="#top" target = "_self">Return to Top</a> Page ...

What is the mechanism behind Angular or JS retrieving data without the need for defining a parameter name?

The title of this question may not fully capture what I am trying to ask. To provide more clarity, consider the following example: .service('Book', function($http) { var bookService = {}; Service.getBook = function() { return $http.g ...

What is the reason behind the failure of next/script with Google reCAPTCHA?

Currently, I am in the process of upgrading from next js version 8 to version 11. I wanted to take advantage of the amazing next js feature for "next/script". However, when I tried to implement it for Google reCAPTCHA using "react-recaptcha": "^2.3.10", th ...

Copying content from one website to another using JavaScript

Currently, I am working on a website which stores data and I require assistance in transferring this data to another site. If you have any suggestions using Javascript or other methods, please let me know. ...

Display HTML content after data has been retrieved using React.useState and useEffect

I'm currently facing an issue with my application that fetches invoice data from the Stripe API, a payment processor. After receiving the invoice data, I attempt to update my state using this.setState({invoiceData: invoices}), where invoices is a stri ...

Function: get the next item from an HTML POST form and register it as undefined when submitted

Encountering a problem with my form - trying to enter a website address/keyword along with a selected filter. The filters are dynamically updated from the database, hence only one option is currently displayed <div class="add-website-content"& ...

Unveiling the mystery of Google's invisible reCAPTCHA integration with WordPress and utilizing Ajax

Trying to integrate Google Invisible reCaptcha into a custom submit form using submit.js (ajax) has been a successful endeavor thanks to the guidance provided in this helpful tutorial on implementing the new Invisible reCaptcha from Google. However, when ...

Achieving Efficiency with Handlebars: Streamlining Remote Template Organization and

I am looking for a way to better organize my HB template by splitting it into different HTML files. In this case, I have created a file called helpers.html. This file contains two script tags: <script id='alert' type='text/template>... ...

When executed, the Node application successfully compiles

I have a TypeScript application that runs smoothly in development mode using ts-node. However, after building the application, I encounter some unexpected warnings and errors. This is my tsconfig.json: { "compilerOptions": { "incremen ...

"Looking for a datetime picker plugin that works well with Bootstrap

Check out this efficient DateTimePicker example. <head> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script> <link rel="stylesh ...

Troubleshoot: Node Express experiencing issues reconnecting to ajax

Here is the initial question that needs to be addressed. I am currently developing an API that links a front-end application (built using node, express, and Ajax) with a Python swagger API. The issue I am facing is that although I can successfully send da ...

How can Request.UrlReferrer be configured using client-side JavaScript? If it can be done, what is the process?

In my application, I heavily rely on Request.UrlReferrer to handle link clicks and maintain a page history for users. Due to new requirements, I now need to navigate to a specific location using <input type="button" /> instead of <a href="mypage. ...

Is the ngShow directive dependent on the parent variable in any way?

There is a piece of code running in the $rootScope to establish a global value for userLoggedIn: mod.run(function($rootScope) { $rootScope.userLoggedIn = false; $rootScope.$on('loggedIn', function(event, args) { $rootScope.userL ...

Step-by-Step Guide to Editing a Firebase Document

Attempting to update a Firebase document results in an error message displayed in the console. Unhandled promise rejection FirebaseError: "Function DocumentReference.update() called with invalid data. Unsupported field value: undefined (found in fie ...

What is the best way to extract function bodies from a string with JavaScript?

I am currently searching for a solution to extract the body of a function declaration by its name from a JavaScript code string within a Node.js environment. Let's assume we have a file named spaghetti.js that can be read into a string. const allJs = ...

Fixing an erroneous value that has been dragged into the drop function with Jquery

I am encountering an issue with my codes and need some assistance in identifying the problem. The data is being dynamically loaded from the database, and I am using a foreach loop to display all items in a draggable div. The issue arises when I drag an it ...

What is the best way to update the state while invoking a component?

Just starting out with react and already hitting a roadblock. I've created an Article Topper component that features a logo, title, and share buttons, which is repeated throughout the site above each article. The issue I'm facing is updating the ...

utilizing YouTube API for real-time updates

Is there a YouTube API equivalent to the HTML5 video's ontimeupdate event that is not documented or known? I have attempted using a setInterval method but it requires additional checks for video play status. Has anyone encountered this problem before? ...