What is the best way to use an object as a key to filter an array of objects in JavaScript?

My data consists of an array of objects:

let allData = [
  {title:"Adams",age:24,gender:"male"},
  {title:"Baker",age:24,gender:"female"},
  {title:"Clark",age:23,gender:"male"},
  {title:"Davis",age:23,gender:"female"},
  {title:"Ghosh",age:23,gender:"female"},
  {title:"Adams",age:23,gender:"male"},
  {title:"Irwin",age:25,gender:"male"},
]

Additionally, I have a filter object with various filter terms:

let filters = {
  title:{filterTerm:[]},
  gender:{filterTerm:["male"]},
  age:{filterTerm:[23]}
}

I attempted to apply multiple filters to the 'allData' using Array.some and Array.includes but encountered issues. Here is the code snippet I used:

const getFilterRows = (rows, filters) => {
    let filterCols = Object.keys(filters)
    if (filterCols.length == 0) {
        return rows
    }
    else {
        let filteredR = rows.filter(i => {
            return filterCols.some((s) => {
                return filters[s].filterTerm.includes(i[s])
            })
        });
        return filteredR
    }
}
let filtered = getFilterRows(allData,filters)

The expected output after applying the filters should be:

[  
 {title:"Clark",age:23,gender:"male"},
 {title:"Adams",age:23,gender:"male"},
]

Answer №1

To filter the data based on specific criteria, you can iterate through each key in the filters object and check if the filter term includes the item being searched in the allData array. Filters with empty terms will be ignored. The following example demonstrates this process and allows for additional items to be added to the filter terms if required.

let allData = [
  {title:"Adams",age:24,gender:"male"},
  {title:"Baker",age:24,gender:"female"},
  {title:"Clark",age:23,gender:"male"},
  {title:"Davis",age:23,gender:"female"},
  {title:"Ghosh",age:23,gender:"female"},
  {title:"Adams",age:23,gender:"male"},
  {title:"Irwin",age:25,gender:"male"}
]

let filters = {
  title:{filterTerm:[]},
  gender:{filterTerm:["male"]},
  age:{filterTerm:[23]},
}

const getFilterRows = (rows, filters) => {
  return rows.filter(row => (
    Object.keys(filters)
      .map(key => filters[key].filterTerm.length ? filters[key].filterTerm.includes(row[key]) : true)
      .every(Boolean))
  )
 }

let filtered = getFilterRows(allData,filters)

console.log(filtered)

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

"Encountering a "404 Error" while Attempting to Sign Up a New User on React Application - Is it a Routing or Port Problem

While working on my React-Express application, I'm facing a "404 (Not Found)" error when attempting to register a new user. It seems like there might be an issue with routing or configuration of the Express server. Being new to React and Express, it&a ...

Dealing with TypeScript issues while implementing Multer in an Express application

import multer, { FileFilterCallback } from "multer"; import sharp from "sharp"; import { NextFunction, Request, Response } from "express"; const multerStorage = multer.memoryStorage(); const multerFilter = ( req: Request, ...

Is it possible to incorporate several modules into nodeJS simultaneously?

I'm a beginner when it comes to NodeJS. I was wondering if it's possible for me to call 2 different JavaScript files using NodeJS and ExpressJS. The idea is to split the work, where I can focus on one file while my partner works on another. So, I ...

Enhance your website with the jQuery autocomplete feature, complete with

Is there a way to incorporate smaller text descriptions alongside the search results displayed on my website? The descriptions are available in the data array used by autocomplete and can be accessed using the .result function by calling item.description. ...

Guide to direct express.js requests straight to 404 page

I need guidance on how to direct a request to a specific route in express.js directly to a 404 error page if the user is not authenticated. Currently, my middleware includes the following code: exports.isAuthenticated = function (req, res, next) { if ( ...

Retrieving the inner content of several paragraph elements, all consolidated into a single string

I'm trying to extract the inner HTML of multiple paragraph elements from a string and I need some help. Here's an example input: let HTML = "<p class="Paragraph" >Hello, World 1!</p><p class="Paragraph" >Hell ...

Steps for dynamically changing the class of a dropdown when an option is selected:

Check out this code snippet : <select class="dd-select" name="UM_Status_Engraving" id="UM_Status_Engraving" onchange="colourFunction(this)"> <option class="dd-select" value="SELECT">SELECT</option> <option class="dd-ok" value= ...

Enter a keyword in the search bar to find what you're looking

I am working on a form where users can select their occupation from a list that is stored in a separate .js file. The list includes various occupations like 'AA Patrolman' and 'Abattoir Inspector'. var occupationSelect = "<select id ...

How to implement Google Tag Manager using the next/script component in Next.js 11?

Version 11 of Next.js recently introduced a new approach with the Script component offering various strategies. To avoid duplicate tags, it is advised to implement Google TagManager using the afterInteractive strategy. In my experimentation: // _app.js ...

What is the best method for distinguishing newly generated unique IDs from the complete list of all IDs?

Recently, I came up with a function that can generate unique IDs: function generate_uuid($needed_ids_num = 1, int $random_bytes_length = 6) { $ids = []; while (count($ids) < $needed_ids_num) { $id = bin2hex(random_bytes($random_bytes_leng ...

Using Bootstrap 5 to display a modal using JavaScript

Creating a sleek gallery using bootstrap 5, and curious about how to activate a bootstrap modal without including "data-bs-..." in the HTML (to prevent repeating those data- attributes multiple times). I have successfully written a functioning JavaScript ...

Passing the value of the selected calendar date to the controller

How can I pass the value generated by this calendar_date_select to the controller? Any suggestions on how to modify the onchange code? <%= calendar_date_select_tag "meeting_date_1", @time, :embedded => true, :time => true, :minut ...

Switching the navigation menu using jQuery

I am looking to create a mobile menu that opens a list of options with a toggle feature. I want the menu list to appear when the toggle is clicked, and I also want to disable scrolling for the body. When the toggle menu is clicked again, the list should c ...

Prioritize loading one script over the other in Next.js/React

In the head section of my webpage, I have included two scripts to load: <Head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script src="/static/js/myscript.min.js" ...

Unlimited Possibilities in Designing Shared React Components

Seeking the most effective strategies for empowering developers to customize elements within my React shared component. For example, I have a dropdown and want developers to choose from predefined themes that allow them to define highlight color, font siz ...

Generate a fresh array from the existing array and extract various properties to form a child object or sub-array

I am dealing with an array of Responses that contain multiple IDs along with different question answers. Responses = [0:{Id : 1,Name : John, QuestionId :1,Answer :8}, 1:{Id : 1,Name : John, QuestionId :2,Answer :9}, 2:{Id : 1,Name : John, QuestionId :3,An ...

Application built with Ember and search engine crawling by Google

I'm attempting to optimize my ember application for search engine crawling. I am aware that Google now supports JavaScript, CSS, and AJAX since October 2015. However, when I use "Fetch as Google" to test my site, I am seeing an empty page with just th ...

Error encountered when attempting to initiate a second screenshare on Chrome due to an invalid state

I am interested in utilizing Screensharing in Chrome. After following a guide and creating an extension to access the deviceId for getUserMedia, I was able to successfully start streaming my screen. However, when I attempted to stop the stream using the pr ...

Javascript continuously swaps out text from distinct strings in a loop

I wrote a loop to split a string and search for certain text to replace it with another string. Here is an example of what I have done: function replaceStr(str, find, replace) { for (var i = 0; i < find.length; i++) { str = str.replace(new RegE ...

Enhance your coding experience with Firebase Autocomplete on VScode

Recently, I installed VScode along with the necessary packages for JavaScript development. As I started writing code involving Firebase, I noticed that the autocomplete feature, which worked perfectly fine in Xcode, was not functioning in VScode. How can I ...