Filtering through an array of objects based on two specific conditions

I am working with an array of objects, each containing properties like category name, categoryId, and a subcategory list which is an array. I need to filter the data based on both the name and values in the subcategory list. Here is a sample of my array:

var statesWithFlags = [
    { subCategoriesList: ['Badges and dentures', 'Cerezens', 'Dental implants'], categoryId: 1, categoryName: "Dental" },
    { subCategoriesList: ['Badges and dentures44', 'Dental implants'], categoryId: 2, categoryName: "Dermatology" },
    { subCategoriesList: ['Badges and dentures', 'Cerezens', 'Dental implants222'], categoryId: 3, categoryName: "Eye" },
    { subCategoriesList: ['Badges and dentures', 'Cerezens', 'Dental implants', 'Cerezens'], categoryId: 4, categoryName: "Ayurvedic" }
  ]

Currently, I have a filtering mechanism that only works for the categoryName property. I would like to modify this to work for the subcategory list as well.

this.statesWithFlags.filter(v => v.categoryName.toLowerCase().indexOf(term.toLowerCase()) > -1)).slice(0, 10))

Answer №1

Confirm whether any of the .some elements in the subCategoriesList contain the specific string you are searching for, or if the name of the categoryName does:

const searchTerm = term.toLowerCase();
this.statesWithFlags.filter(item => (
  item.subCategoriesList.some(subCategory => subCategory.toLowerCase().includes(searchTerm))
  || item.categoryName.toLowerCase().includes(searchTerm)
))
  .slice(0, 10);

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

The essential guide to coding Javascript/Ajax in conjunction with Chart.js

I have successfully implemented a controller action in my MVC project that generates a JSON record with the required components. The challenge I am facing now is integrating this data into a pie chart using chart.js. The pie chart should display the counts ...

How to Easily Add GitHub NPM Packages to Your SAPUI5 Web IDE

Looking to integrate an NPM package from Github into SAPUI5 using the WebIde Framework. Package Link: https://github.com/commenthol/date-holidays/blob/master/README.md#usage Primary Issue: Need a file with the library for importing and copying into the W ...

``There seems to be an issue with the functionality of JSON.stringify

Upon attempting to use the JSON.stringify() method to convert an array of strings into a JSON object for passing to a PHP script, I encountered an issue where the method did not return any meaningful output. The code provided is the only one handling the ...

Ways to disable the caching feature in Google Chrome

When I am working on CSS and JS around a page, I need to disable the cache mechanism in Google Chrome browser. A trick is to open Chrome DevTools, which automatically disables the cache mechanism (you can configure this in the settings section). Are ther ...

"Performing validation on a number input by using the ng-change event

Im using a number input that dynamically sets the min and max values based on another form field. I have two scenarios: Level 1: Min = 2, Max = 50 Level 2: Min = 5, Max = 1000 I've set up an ng-change event on the input field to check if the entere ...

What causes my scene to appear black until OrbitControl is activated in ThreeJS?

What causes the scene in ThreeJS to only appear after clicking and moving the cursor? The page remains black until I interact by clicking and moving, then everything shows up. I'm stumped on what the issue could be. Any assistance would be greatly ap ...

Running npm commands, such as create-react-app, without an internet connection can be a

Currently, I am working in an offline environment without access to the internet. My system has node JS installed. However, whenever I attempt to execute the npm create-react-app command, I encounter an error. Is there a workaround that would allow me to ...

"Implementing a spinning wheel feature using HTML and JavaScript to dynamically add components

Trying to add a needle on top as a stopper. Previously, a custom-created SVG arrow was used, but now attempting to replace it with a needle.png at the same position. Any suggestions? Various options were tried to add an image in JS, but none of them work ...

Encountering a problem when verifying if the data is in JSON format using JavaScript

I'm using JavaScript to determine whether an input value is in JSON format, but I've encountered a problem with a specific value. Below is my code explanation. isJSON = async(str) => { try { return (JSON.parse(str) && !!str); ...

Demystifying Iron Ajax: Unraveling the process of parsing an array of JSON objects from a successful

When making an AJAX call to the server, I receive a response in the form of an array of objects as JSON. [{"dms":[{"serialNo":"EG0022","status":"running","firmwareStatus":"ok","latitude":37.8688,"longitude":-144.2093,"toolType":1},{"serialNo":"EG0022","st ...

Using JavaScript to Set Values and Manage Session State in APEX

Trying to utilize JavaScript in Oracle APEX to set the value and session state. See below function that is being called: function updateItemValue(element) { $s('P2020_SELECTED', element); apex.server.process ('MY_PROCESS', { ...

Seeking guidance on capturing the correct error message when using JSON stringify?

Imagine I have an object structured as follows var obj = { "name": "arun" age } After attempting JSON.stringify(obj), it results in an error due to the improper structure of the obj. I am interested in capturing this error displayed in the console and pr ...

What is the best way to begin IMA HTML5 SDK ads with sound off?

One challenge I encountered was getting autoplay video to work on iOS 10 using HTML5. To achieve this, I utilized the following code: <video autoplay loop muted playsinline controls> <source src="http://distribution.bbb3d.renderfarming.net/vi ...

Creating a dynamically generated JavaScript array using the JSON format

I am in need of creating an array of JSON data. Here is an example: [ { "DataCategoryGroupId": "22222222-2222-2222-2222-222222222222", "AnswerOptionIds": [ "76e32546-0e26-4037-b253-823b21f6eefb", "10d02a3e-9f9f- ...

What is the sequence of the middlewares for error handling and handling of 404 errors?

The express.js website has confused me with contradictory statements regarding error-handling middleware. According to one page, you should define error-handling middleware last, after other app.use() and routes calls. However, another page states that you ...

As you loop through, generate an associative array by collecting values from method invocations

My goal is to create an array that has a specific structure: Array ( [123 Smith St, Begora] => L1234 [55 Crumble Road, Mosmana] => L2456 [99 Jones Ave, Gestana] => L3456 ) This array will be used to populate a select menu on an HTML form. To ach ...

Exploring the connection between Jquery and Javascript event handling within ASP.NET C# code-behind, utilizing resources such as books and

It seems that Jquery, Javascript, and AJAX are gaining popularity now. I am interested in learning how to use this functionality within C#. Do you have any recommendations for resources or books that teach JavaScript from a C# perspective on the web? Not ...

Creating multiple routes within a single component in Angular without triggering unnecessary redraws

Within the ChildComponent, there is a reactive form that allows for data entry. Upon saving the filled form, the route should be updated by appending an id to the current route. Currently, when saving, the component renders twice and causes screen flicke ...

Issue with Axios response processing

I need to upload a new document into a database using Axios in React. I have successfully implemented the functionality, but I also want to display a message in the console saying "New post has been inserted". This is my front end code: newTodo(todo){ ax ...

AJAX initiates automatically upon page load and also at specified time intervals

Can anyone guide me on how to make my AJAX work when the document loads and run every 20 seconds? I have managed to set it up for running every 20 seconds, but I'm facing issues with getting it to work when the document is loaded. Any assistance on th ...