Utilizing a dropdown selection value to filter a list in JavaScript

I have an array of objects where I need to filter based on a dropdown selection.

const itemsList=[{
"id":"123",
"problems":{
    "causes":[ 
         {
        "SSEnabled": true,
        "IndusEnabled": false,
        "LogEnabled": true
        }
    ]
}
},
{
"id":"234",
"problems":{
    "causes":[
          {
        "SSEnabled": false,
        "IndusEnabled": false,
        "LogEnabled": true
        }
    ]
}
}]

There is a dropdown to filter by SSEnabled cause with options "show", "nofilter", "exclude".

The goal is to filter the list based on the dropdown selection.

If "show" is selected for "SSEnabled", the item with "SSEnabled": true should be the result (i.e. id: "123").

If "exclude" is selected for "SSEnabled", the item with "SSEnabled": false should be the result (i.e. id: "234").

If "nofilter" is selected, the filter should be ignored (i.e. id: "123", id: "234").

filterList(filterType, filterValue, itemsList) {
   // filterType: SSEnabled (dropdown type changed)
   // filterValue: show, exclude, no filter
itemsList.map((items) => {
  if (
    items &&
    items.problems &&
    items.problems.causes &&
    items.problems.causes.length
  ) {
    items.problems.causes.filter((cause) => {
       if (cause[filterType] === true && filterValue === 'show') {
        return true;
      }
      if (cause[filterType] === false && filterValue === 'exclude') {
        return true;
      }
    });
  }
});

console.log(itemsList, 'filtered List');
}

However, the list is not being filtered as expected. Assistance with filtering is appreciated.

Answer â„–1

An effective approach is to create a lookup of functions that implement your desired logic, and then pass the appropriate function to some() (or find()). You can specify the function to use in the field parameter, such as show or exclude, and the filtering criteria in the key parameter, like SSEnabled.

const itemsList=[{"id":"123","problems":{"causes":[ {"SSEnabled": true,"IndusEnabled": false,"LogEnabled": true}]}},{"id":"234","problems":{"causes":[{"SSEnabled": false,"IndusEnabled": false,"LogEnabled": true}]}}]

// define the filtering logic based on the keyword
// returns items where some of the causes match the condition
const filters = (field, key ) => {
    let options = {
     show:     (i) => i[key] == true,
     nofilter: (i) => true,
     exclude:  (i) => i[key] == false
    } 
    return options[field]
}

// filter using the function defined above:

let SSEnabled = itemsList.filter(item => item.problems.causes.some(filters('show', 'SSEnabled')) )
console.log(SSEnabled)

let SS_not_enabled = itemsList.filter(item => item.problems.causes.some(filters('exclude', 'SSEnabled')) )
console.log(SS_not_enabled)

let LogEnabled = itemsList.filter(item => item.problems.causes.some(filters('show', 'SSEnabled')) )
console.log(LogEnabled)

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

Is there a way to modify the background color of ::before when hovering over it?

I have a ul-li list and when i hover last li ::before element looks white and not so good. I want to change it when i hover the last li element. How can I achieve this? Here are my codes: <div className="dropup-content"> <ul> & ...

Anticipated the start of an object but instead encountered a string at line 1, column

I seem to be encountering an issue with my code that utilizes the Gson library. Upon running, the following error is thrown: 5596-5596/be.appmax.ktsjjt E/AndroidRuntime﹕ FATAL EXCEPTION: main com.google.gson.JsonSyntaxException: java.lang.IllegalStateE ...

Limit the API call to only respond to requests from the localhost

I'm currently working on a website that uses API calls within the same node project. I would like to restrict most of these API calls to only be accessible by the localhost website. Is there a way to achieve this without implementing OAuth and simply ...

The image fails to load smoothly in the midst of an ajax operation

Here is my code snippet... div used for displaying content along with a loading image: <div id="adS" style="float: left; width: 70%"> <div id="loading-image" style="background-image: url('images/processing.gif'); display: none;"> ...

Is there a way to combine JavaScript, CSS, and HTML code in a single HTML document?

Is there a way to include both <script> and <style> elements within the same HTML body? <html> <head> <title>My site title</title> </head> <body> </body> </html> I am looking to in ...

Understanding the Issue: Newtonsoft.JSON Failing to Deserialize Stringified JSON Schemas

Currently, I am retrieving data from a client that signifies a function within a ChatGPT API request. The detailed documentation can be accessed at: . My assumption was that the JSON received would go through parsing by Newtonsoft.Json, and subsequently, ...

What is the best way to structure the ImageMagick argument in a Powershell script to draw intersecting lines that connect the hexagonal vertices?

Looking to engage my nephew in design and coding by setting up a project, while also learning myself. The code snippet below appears to be functional, but I am facing challenges in optimizing it. Specifically, I am struggling to figure out how to set $draw ...

Leveraging JavaScript within a Polymer component

I have an object made with polymer: <newfolder-element id="newfolderelement" popupStyle="width: 362px; height: 100px;"> <span class="title">Create a new folder</span> <input type="text" class="ginput" style="width: 350px; padd ...

Display or conceal a <div> segment based on the drop down selection made

A dropdown menu controls the visibility of certain div elements based on the selection made. While this functionality is working for one dropdown, it's not working for another even though the code is very similar. I've tried various solutions but ...

State management at its core with integrated functionalities

I'm exploring different ways to manage application state within Angular 18 using its built-in features. Would it be effective to start with a simple service that utilizes dependency injection (DI)? As someone new to Angular 18, I'm a bit confuse ...

How can I use jQuery to trigger a left or right movement on a Waterwheel Carousel?

I'm a beginner in jquery and I'm looking to navigate my Waterwheel Carousel to the left or right using buttons. Let's say I have a button for moving to the right. How can I achieve this using the Waterwheel Carousel function? I've atte ...

Interact with a JSON API using JavaScript by incorporating dynamic user input

Recently, I delved into tutorials on utilizing JSON data and JavaScript. Feeling inspired, I decided to create a simple app using an API. However, I encountered a hurdle and I'm struggling to identify its cause. The problem seems to be related to how ...

Creating Custom Checkboxes with Individual States in React Native

Currently, I am facing an issue with the checkboxes associated with a list of products that are generated dynamically in a loop. All checkboxes are sharing the same state, so when one is checked, they all get checked. I am using React Native and the chec ...

What is the process for uploading images in the backend of a Next.js API?

I am working with Next.js and an API. I need to be able to upload two files and include one text input field using the API backend. I have been struggling to find a solution for uploading files with different fields along with a single text input field in ...

Tips on converting a JSON array into a strongly-typed C# class instance via deserialization

This question seems quite similar to another one posted here. Despite my efforts to convert the provided solution into C#, I am not a JSON expert and find myself confused. The challenge lies in deserializing the JSON response from the Kraken OHLC endpoin ...

Trigger a popup using the javascript .link() method

I am currently using ag-grid to present JSON data. When the values are located within nested objects, I have to utilize a valueGetter from the grid API to map to the appropriate value. The value getter returns a value for each row and the grid matches it t ...

What could be the reason for the handleOpen and handleClose functions not functioning as expected?

I am facing an issue with my React component, FlightAuto, which contains a dropdown menu. The functionality I'm trying to achieve is for the dropdown menu to open when the user focuses on an input field and close when they click outside the menu. Howe ...

Error Message: Unhandled Exception while working with JSON in Flutter: _InternalLinkedHashMap type encountered

As a newcomer to the world of Flutter, I encountered an error that I am having trouble understanding. Below is my network handler code: Future get(String url) async { final String? token =await storage.read(key: "token"); url = formatter ...

Transform the code to utilize AJAX jQuery

Recently, I developed a Chrome Extension that extracts data from the data-href attribute and applies it to the href attribute from a Google Search. Below is the current implementation: $(document).on("DOMSubtreeModified", function() { var e = $("#sear ...

"Displaying events on fullcalendar using data retrieved from a PHP server with a

After creating my first RESTful PHP server, specially designed for responding to fullcalendar events callback, I encountered a strange issue. Even though the output from my server matches the string produced by the json-events.php file in the fullcalendar ...