Creating a custom dynamic function for my Angular application

I am facing an issue with dynamically writing this code.

How can I create a function called testtest in a dynamic way, considering that the data might have different keys and values in the future?

Here is how my JSON object looks:

data = [
    {
      name: 'John',
      id: 1,
      colour: 'Green',
      pet: 'Dog'
    },
    {
      name: 'Sarah',
      id: 2,
      colour: 'Purple',
      pet: 'Cat'
    },
    {
      name: 'Lindsay',
      id: 3,
      colour: 'Blue',
      pet: 'Lizard'
    },
    {
      name: 'Megan',
      id: 4,
      colour: 'Orange',
      pet: 'Dog'
    }
];

Additionally, I have a set of filter values defined as:

filterValues = {
    name: '',
    id: '',
    colour: '',
    pet: ''
};

Now, let's look at a function implementation:

createFilter(): (data: any, filter: string) => boolean {
    let filterFunction = function(data, filter): boolean {
        let searchTerms = JSON.parse(filter);
        let result = this.testtest(data, searchTerms);
        return result;
    }
    return filterFunction;
}

testtest(data, searchTerms): boolean {
    return data.name.toLowerCase().indexOf(searchTerms.name) !== -1
        && data.id.toString().toLowerCase().indexOf(searchTerms.id) !== -1
        && data.colour.toLowerCase().indexOf(searchTerms.colour) !== -1
        && data.pet.toLowerCase().indexOf(searchTerms.pet) !== -1;
}

Answer №1

Here is a way to achieve the desired outcome:

performSearch(data, searchTerms): boolean {
var result = false;
for (var property in data) {
if (data.hasOwnProperty(property)) {
     result = (property.toLowerCase().indexOf(searchTerms[property]) !==-1)
     if (!result){
       return result;
     }   
}
else {
  return result;
}
}
}

Answer №2

Utilizing ES6, a possible solution could be-

data.filter(obj => Object.keys(obj).some(key => obj[key] == searchText));

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

Handle and manage errors within the controller in Express.js to prevent the further execution of asynchronous functions

Consider a scenario where there is an API endpoint /register, designed to register new users in an application. The function utilized is asynchronous, as an attempt is made to incorporate an asynchronous process within an AuthController when performing pas ...

Duplicate a DOM element and incorporate animation into it

After extensively researching articles and documentation on this topic, I have yet to find a solution that aligns with the approach I am attempting to implement. My scenario involves an array of category items which contain a nested array of products be ...

What is the best way to manually initiate an interval in rxjs?

periodicGatewaysUpdate() { return interval(GATEWAY_REFRESH_INTERVAL) .pipe( startWith(0), takeUntil(this.stopAutoRefresh), exhaustMap(() => this.fetchAllData()) ).subscribe( (gateways) => { this.gateways = gateways; ...

Arrange the "See More" button in the Mat Card to overlap the card underneath

I'm currently working on a project that involves displaying cards in the following layout: https://i.stack.imgur.com/VGbNr.png My goal is to have the ability to click 'See More' and display the cards like this: https://i.stack.imgur.com/j8b ...

What are the steps for implementing persisting and rehydrating data in redux-toolkit?

After setting up the redux-persist with react-toolkit as recommended in the documentation, I found myself needing to perform some operation on rehydrate. Unfortunately, my attempts have been unsuccessful so far. Here is what I have tried: ... import { RE ...

You are unable to define a module within an NgModule since it is not included in the current Angular compilation

Something strange is happening here as I am encountering an error message stating 'Cannot declare 'FormsModule' in an NgModule as it's not a part of the current compilation' when trying to import 'FormsModule' and 'R ...

Managing errors with promises in Angular 6 using SSH2

Attempting to manage ssh2 error messages using Angular has been a bit challenging for me. I tried implementing a promise to handle it, but unfortunately, it's not working as expected. Being new to this, I apologize if my approach is inadequate, and I& ...

Retrieving document attributes from a Mongoose Model with the help of Typescript

Incorporating Typescript with Mongoose, my aim is to retrieve properties from a Model. Taking the illustrated UserModel as an example import mongoose, { Schema } from 'mongoose'; const userSchema: Schema = new mongoose.Schema({ _id: mongoos ...

Search for an element deep within a tree structure, and once found, retrieve the object along with the specific path leading to

I created a recursive function to search for a specific object and its path within a tree structure. However, when I changed the target ID (from 7 to 10) in the function, I encountered an error: "message": "Uncaught TypeError: Cannot read ...

The implementation of the "setValue" function from react-hook-form resulted in the generation of over 358,000 TypeScript diagnostics for various types

In my experience, I have frequently used react-hook-forms and `setValue` in various parts of my application without encountering any issues. However, I recently came across a problem while compiling in a newly created branch based on the main branch. Desp ...

What is the best way to initiate a class constructor with certain parameters left out?

Currently, I am facing a challenge while trying to pass various combinations of arguments to a class constructor. The constructor has 2 optional arguments. Here is the code snippet: class MyClass { foo(a, b) { return new MyClass(a, b); } bar( ...

Passing values in onPress method of TouchableOpacity without using arrow functions or bind function can be achieved by using JSX props. Remember not to use arrow functions in JSX props

I am working on a React Native project and I have a TouchableOpacity component in my view with an onPress method. I want to avoid using arrow functions and bind functions in the onPress method as it creates a new function every time. My goal is to pass par ...

Targeting multiple browsers in an Angular 11 project with scss: A comprehensive guide

for instance: i'm currently animating the ::placeholder pseudo element when ::focus is active input::placeholder{ color: grey; transition: all 400ms ease; position: absolute; top: 35%; font-size: 15px; } inpu ...

The parameter type 'string[]' cannot be assigned to the parameter type '("a" | "b" | "c")[]' in TypeScript

/** * Function to pick specific keys from an object. */ function pick<T, K extends keyof T> (obj: T, keys: K[]): Pick<T, K> { return keys.reduce((result, key) => { result[key] = obj[key]; return result; }, {} as any); } const ...

Incorporating TypeScript into an established Node.js Express project

I am keen on building a Node.js Express application using TypeScript. I have been watching several tutorials online to learn how to integrate TypeScript in Node.js, and fortunately, it is functioning as intended. However, the .ts files are currently bein ...

The header component does not update properly post-login

I am currently developing a web-app using Angular 8. Within my app, I have a header and login page. My goal is to update the header after a user logs in to display information about the current logged-in user. I attempted to achieve this using a BehaviorS ...

In Ionic 2, trying to access the IONIC_ENV variable consistently results in it being undefined

Does anyone know how to access the IONIC_ENV variable in order to switch between using the API URL for production and development environments? Every time I try to check it, it returns undefined. process.env.IONIC_ENV I might need to run or add another c ...

Utilizing a loaded variable containing data from an external API request within the useEffect() hook of a React component

Essentially, I have an API request within the useEffect() hook to fetch all "notebooks" before the page renders, allowing me to display them. useEffect(() => { getIdToken().then((idToken) => { const data = getAllNotebooks(idToken); ...

Leveraging NFC in Ionic 2

I've been attempting to create a function that triggers a phone vibration whenever an NFC card is detected. I'm utilizing Ionic 2 and this plugin: https://github.com/chariotsolutions/phonegap-nfc This is the approach I tried. In the .ts file : ...

"Encountering a TypeScript error when using React Query's useInfiniteQuery

I am currently utilizing the pokeApi in combination with axios to retrieve data import axios from 'axios' export const fetchPokemonData = async ({ pageParam = "https://pokeapi.co/api/v2/pokemon?offset=0&limit=20" }) => { try ...