Filtering data dynamically in Angular - a step-by-step guide

Looking to dynamically filter data based on various interfaces? Let's explore how to achieve this flexibility:

export interface Country {
    cId: string;
    cName: string;
    cFlag: string;
}

export interface Address {
    aId: string;
    aName: string;
    aStreet: string;
}

An existing method filters data from one type of interface, but we aim to make it versatile for any interface. Here's the updated code snippet:

public data: any[] = [];

var filteredObject = this.data;
var { search } = query;

if (search) {
    search = search.toLowerCase();
    filteredObject = filteredObject.filter((f) => {
    f.includes(search);
    ({ firstColumn, secondColumn, thirdColumn }) =>
        firstColumn.toLowerCase().includes(search) ||
        secondColumn.toLowerCase().includes(search) ||
        thirdColumn.toLowerCase().includes(search)
    });
}

The key is making the columns dynamic based on the provided interface type. For example, if it's Country, use cId, cName, cFlag instead of static values.

Answer №1

According to @berk-kurkcuoglu's suggestion, one can utilize Object.values and some within the context of filter. By incorporating Optional Chaining and the use of toString, it becomes possible to filter various types of fields excluding object type fields.

const data: any[] = [
  { cId: 1, cName: "Peru", cFlag: 2 },
  { aId: 1, cName: "work", cStreet: "93 Mcguire Plaza" },
];

let filteredObject = data;
let search = "pe";

if (search) {
  search = search.toLowerCase();
  filteredObject = filteredObject.filter((f) => {
    return Object.values(f).some(v => {
      // if (typeof v !== "string") return false;
      return v?.toString().toLowerCase().includes(search);
    });
  });
}

console.log(filteredObject);

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

How do I retrieve the data returned from the component.ts file in Angular Material's MatTableModule when it is not directly inside the mat-table in the template?

I'm currently working on an Angular 5 project where I have integrated a table to display data using MatTableModule from angular material. This specific inquiry consists of two parts. Within my project, there is a service that sends a GET request to t ...

Having trouble with Angular2 + Webpack DefinePlugin integration?

Attempting to launch the Angular2 app following the tutorial on angular.io has been quite the journey for me. Angular2 with Webpack Tutorial on angular.io The installation process went smoothly, despite a few minor obstacles, considering I'm using U ...

What is the reason behind the return type of 'MyType | undefined' for Array<MyType>.find(...) method?

Currently, I am in the process of developing an Angular application using TypeScript. As part of this project, I have defined several classes along with corresponding interfaces that align perfectly with their respective properties: Map: export class Map ...

What is the best way to address dynamic meta tags in Angular server-side rendering (SSR

My Angular application uses server side rendering, and I am dynamically loading the meta tags content from the backend. Despite seeing the proper content in the HTML, Facebook's debugger does not seem to recognize the tags. Has anyone else encountered ...

Angular, manipulating components through class references instead of creating or destroying them

I am exploring ways to move an angular component, and I understand that it can be achieved through construction and destruction. For example, you can refer to this link: https://stackblitz.com/edit/angular-t3rxb3?file=src%2Fapp%2Fapp.component.html Howeve ...

What is the method for deducing the names that have been announced in a related array attribute

In my definitions, I have identified two distinct groups: Tabs and Sections. A section is encompassed by tabs (tabs contain sections). When defining sections, I want the tab names to be automatically populated by the previously declared sibling tabs. But ...

The input type '{}' does not match the expected type 'Readonly<IIdeasContainerProps>'. The property '...' is not found in the type '{}'

Having recently started using TypeScript, I'm encountering some issues when attempting to execute this code snippet. Error The error message reads as follows: Failed to compile 13,8): Type '{}' is not assignable to type 'Readonly &l ...

What is the best way to limit the types of function parameters in TypeScript based on whether the parameter index is even or odd?

My goal is to create a function with an unlimited number of parameters, where the type of each parameter is determined by whether its index is odd or even. For example: flow(isMachineReady(), 'and', isWaterHot(), 'or', isMilkHot(), &ap ...

Structuring an Angular 2 Project with Several Modules

As I delve into the world of Angular 2+ development with my first application, I find myself faced with challenges on how to effectively structure it. The initial phase involves implementing user authentication features such as login and account creation. ...

Adding Crypto-JS to an Angular 2 application

For my Angular 2 development using TypeScript and SystemJS, I needed to integrate crypto-js. Here is the configuration in my systemjs.config.js file: (function (global) { System.config({ paths: { 'npm:': 'node_modules/' ...

Developing an Angular service to incorporate retry functionality for $http.get requests in Typescript

Looking to add offline support to my angular web-app, but struggling to get my simple retry function to function properly. My service code is as follows: constructor($http: ng.IHttpService, private $q: ng.IQService, private $interval: ng.IIntervalService, ...

Angular2: The provided arguments do not correspond to any valid call signature

I have developed my own Observable service implementation import { Injectable, EventEmitter, Output} from '@angular/core'; @Injectable() export class CustomObservableService { data = []; @Output eventEmitter:EventEmitter = new EventEmit ...

Page Breaks - Patience in anticipation of dataSource readiness

I am facing an issue with my pagination service and component. The dataSource appears empty when the page is loaded for the first time, but by the second time it is populated and I can display the dataTable and paginate successfully. Is there a workaround ...

Exploring Angular: How to access ViewChild from a dynamically loaded component

One of my components includes a ViewChild element like this: @ViewChild('overView') content: ElementRef; I am dynamically loading this component in the following way: let overviewComponent = this.vcr.createComponent(OverviewComponent); let conte ...

What is the purpose of code indentation or adding semicolons in WebStorm?

In my Angular project, I am encountering a semicolon issue with arrow functions while using WebStorm. https://i.sstatic.net/R3Wmy.png By removing the semicolon, I was able to resolve the error. However, whenever I format my file using Command + Option + ...

obtaining the value of an input using typescript (put request)

Does anyone know how to extract input values and store them as JSON? I'm having trouble with accessing the input value in this scenario. When I attempt document.querySelector("todo-text").value, it results in an error. const NewTodo: React.FC<NewT ...

Bringing tex2max.js into an angular application using npm and index.html

Every time I attempt to import tex2max with the command declare var tex2max: any;, I encounter a ReferenceError: tex2max is not defined. Interestingly, this issue does not arise with other npm packages. Despite trying various methods such as installing the ...

Array[object..] logical operators

I am currently working with Boolean and logical operators using code like this: Just so you know, I want to convert object values and logic into an array to perform logical operations. For example: object1.logic object.operators object2.logic as either tr ...

Creating a Dynamic Download Link in Angular 6

Hello everyone, I need assistance in making my download feature dynamic. Here is my HTML code: <button class="btn btn-primary" (click)="downloadMyFile({{account.students[0].schoolId}})"><i class="fa fa-file-pdf-o"></i> Download</butt ...

Is it possible to use an object's attribute as a switch case in TypeScript with useReducer?

I am attempting to convert switch case String into an object, but for some reason typescript is misunderstanding the switch case within useReducer: Prior to version update, everything was functioning correctly: export const LOGIN_USER = "LOGIN_USER&qu ...