Filter Angular by columns that change dynamically

I have a filter function that works well when I use a static column name like this:

this.listOfData = this.listOfData.filter((item: DataItem) =>
  item.name.toLowerCase().indexOf(newValue.toLowerCase()) !== -1
);

Note: item.name

However, I need to search in every column of the item, how can I accomplish that?

Note: name needs to be dynamic.

The columns in my ListofData are as follows:

listOfData({
  id: 
  ticket_number: 
  status_name:
  name: // the current function only targets this value.
  created_by_full_name:
  receive_time:
  response_time:
  resolution_time:
})

Update

Following Allabakash's answer, I have the final code below, but it is generating various typescript errors:

ngOnInit(): void {
  // This listens to the input value from the service and takes action on change.
  this.globalSearchService.searchTerm.subscribe((newValue: string) => {
    // Here is where you would apply your current filtering logic.
    this.searchTerm = newValue;
    if(newValue != null) {
      this.visible = false
      this.listOfData = this.listOfData.filter((item: DataItem) =>
      let keys = Object.keys(item);
      for (let key of keys) {
         if (typeof item[key] === 'string' && 
           item[key].toLowerCase().indexOf(newValue.toLowerCase()) !== -1) {
           return true;
         }
       }
       return false;
      );
    }
  });
}

Answer №1

If you are looking to dynamically search across all properties, you can utilize the following approach.

this.listOfData = this.listOfData.filter((item: DataItem) => {
     let keys = Object.keys(item);
     for (let key of keys) {
       if (typeof item[key] === 'string' && 
         item[key].toLowerCase().includes(newValue.toLowerCase())) {
         return true;
       }
     }
     return false;
    }
  );

Answer №2

To easily tackle this issue with just one line of code, you can leverage ES6. Check out the example below which demonstrates how to achieve this using vanilla Javascript.

    const initialListOfItems = [
      { name: 'Peter', surname: 'John'},
      { name: 'Judas', surname: 'James'},
      { name: 'Paul', surname: 'Peter'},
      { name: 'Petrover', surname: 'Junior'}
    ]

    const searchTerm = 'pet'

    const filteredList = initialListOfItems.filter(
      item => Object.keys(item).some(prop => 
        (new RegExp(searchTerm.toLowerCase())).test(item[prop].toLowerCase())
    ))

    console.log(filteredList)

If you are dealing with typescript, here is how you can handle it:


this.filteredList = initialListOfItems.filter(
   (item: any) => Object.keys(item).some((prop: any) => 
     (new RegExp(searchTerm.toLowerCase())).test(item[prop].toLowerCase())
 ))

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

Retrieve the currently logged-in user whenever the component is rendered using React's Context API

For my small React project, I am utilizing ContextAPI. Whenever I hit the /login endpoint, I store the user's token using an HttpOnly Cookie. Below is the code for UserContext.js, which encapsulates all components (children) within App.js import axio ...

Having trouble accessing the database in Angular and Ionic through a provider on a Tabbed page

I created a Home page with tabs using Ionic 3 and Angular. The tabs are named Stats and Calc. When clicking on the Stats tab, it triggers the class/component stats.ts (displayed below). This component utilizes two providers: CropProvider and ContractProvi ...

The Typewriter Effect does not appear alongside the heading

For my portfolio website, I am using React to create a unique typewriter effect showcasing some of my hobbies. Currently, the code is set up like this: "I like to" [hobbies] However, I want it to display like this: "I like to" [h ...

I'm having trouble modifying the backdrop to 'true' or removing it after setting it to 'static' in Bootstrap. Can anyone help me troubleshoot this issue?

I have been encountering an issue with changing the backdrop setting from 'static' to 'true' in Bootstrap modal. Here is the code I am using: $('#modal').modal({backdrop: 'static', keyboard: false, show: true}); ...

The routing feature functions properly on localhost but encounters issues on the live server

There seems to be an issue with this code. While it works perfectly on localhost, it doesn't function as expected on a live Apache server. I have already specified the homepage in the package JSON file and included an htaccess file. However, when acce ...

Having trouble sending a post request to the /register endpoint

Recently, I've been working on setting up a user registration process using Node.js. However, I've encountered an issue where every time I send a POST request with email and password, I receive a 404 error in Postman stating "Cannot POST /signup" ...

Tips for expanding button width in 'react-native-swipeout' to enable swipe action on ListView row (React Native)

Currently, I am exploring how to implement the component found here: https://github.com/dancormier/react-native-swipeout My goal is to have the row swiped all the way. Is there a method to increase the button width so that it covers the entire width of th ...

Encountered error: Unable to locate module - Path 'fs' not found in '/home/bassam/throwaway/chakra-ts/node_modules/dotenv/lib' within newly generated Chakra application

Started by creating the app using yarn create react-app chakra-ts --template @chakra-ui/typescript. Next, added dotenv with yarn add dotenv Inserted the following code block into App.tsx as per the instructions from dotenv documentation: import * as dote ...

Tips for setting up Nginx with Node.js on a Windows operating system

I am looking to set up Nginx on my Windows machine in order to run two node applications. Can anyone provide guidance on how to accomplish this? I have attempted to download Nginx 1.6.3, but have had trouble finding instructions specifically for running i ...

Guide on accessing device details with Angular2 and Typescript

I'm working on populating a table with details using TypeScript, but I need some assistance. 1. Device Name 2. Device OS 3. Location 4. Browser 5. IsActive I'm looking for a solution to populate these fields from TypeScript. Can anyone lend me ...

Integrating Project Tango with Ionic and/or Angular in a cutting-edge mobile application

I'm currently working on a mobile app project and I could use some advice. The majority of the app can be developed using angular.js (and possibly ionic) JavaScript technology. However, there is one aspect that requires integration with an API, specif ...

Navigating with finesse in Angular2

My goal is to generate dynamic routes using the index names from my elastic index. I successfully implemented dynamic routing by manually adding some names, but encountered an issue when trying to insert routes with my elastic index names. In my app.routi ...

Enhance your MongoDB with the power of JQuery and ExpressJS combined with the magic

I've successfully implemented a delete function using type: 'DELETE', and now I'm attempting to create an UPDATE function. However, I'm unsure if I'm approaching this correctly. Here's the code I've written so far: ...

How can I retrieve file input values in angularjs?

Currently, I am working on a simple application in AngularJS with the Slim framework. This application includes a form where users can input data such as their name, categories, currency, and an image file. While I am able to successfully retrieve data fro ...

Material-UI: Issues with functionality arising post library update

I recently switched from material-ui version 0.14.4 to 0.15.4 and encountered some issues while trying to make my code work. Below is an excerpt from my code: var React = require('react'), mui = require('material-ui'), LoginDialog ...

How can I send parameters to an HTML file using Node.js?

In my current code res.sendfile('./home.html',{user:req.user}), I need to figure out a way to access the user parameter directly in the HTML file without relying on a template engine. Can anyone suggest how this can be achieved? ...

What is the NodeJs Event loop and how does it work with libuv and V8

NodeJs is made up of the V8 engine and the libuv library. The V8 engine has its own event loop with a call stack, event queue, and micro task queue to run our main code. The libuv also has an event loop with phases like times, callbacks, poll, check, and ...

Manipulate text within a text area using jQuery

Good afternoon. How can I use JavaScript to update the text in a textarea input? I currently have some content in my textarea that includes a PublisherImprintName tag, and I want to remove it using jQuery. <PublisherInfo> <PublisherName>A ...

Tips for choosing one specific element among multiple elements in cheerio nodejs

Currently, I'm attempting to extract links from a webpage. However, the issue I'm encountering is that I need to extract href from anchor tags, but they contain multiple tags with no class within them. The structure appears as follows. <div c ...

Troubleshooting date range validation in jQuery

I am facing an issue in my code where I have a set of start and end date fields that need to be validated to ensure the start date comes before the end date. I am currently using the jQuery validation plugin for this purpose. For reference, here is the li ...