Retrieve the value of "this" dynamically in Typescript using a string variable

Currently my project is using Angular 10 and I have a specific requirement. In the function below, I need to pass in a filter variable dynamically so that I can extract the startValue property from it.

let filter = "AgeRange";

ValidateValues(endValue: string,filter:string){
startValue = this.SearchFields.{filter}.Start;  

}

The structure of SearchFields is as shown:

export class SearchFilters{
    Gender: string = "Select";
    AgeRange:StartEndValues = new StartEndValues;
    CsaScore: StartEndValues = new StartEndValues;
    FarmSize: StartEndValues = new StartEndValues;
    PracticeCategory:string = "Select";

    public constructor(init?:Partial<SearchFilters>){
        Object.assign(this, init);
    }
}

export class StartEndValues{
    Start: string = "Select";
    End: string="Select";

    public constructor(init?:Partial<StartEndValues>){
        Object.assign(this,init)
    }
}

Answer №1

To optimize your approach, consider storing your filters as an Object instead of a class:

const searchFilters = {
  ageRange: StartEndValues = new StartEndValues(),
  csaScore: StartEndValues = new StartEndValues(),
  farmSize: StartEndValues = new StartEndValues(),
}

This method allows you to easily access individual filter ranges using bracket accessor notation:

filter = "ageRange";
startValue = searchFilters[filter].start;

For further information, refer to this resource:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

In addition to this particular issue, it's advisable to exercise caution when storing diverse forms of filters in a single class or object. Instead of storing data in that manner and handling filtering logic elsewhere, consider defining each filter as a pure function with consistent parameters.

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

Issues with installing the forked version of the npm/Angular 8 package differ from the original installation method

After utilizing git, forking, branching, pull requests, and npm in my standard nodejs projects without any major issues, I encountered an unexpected problem. When trying to Fork an Angular repository and integrate this forked version into my project, I not ...

Is there an issue with loading a local image? Could it be related to Angular or Chrome

Currently, I am working on a webpage that is designed to showcase a collection of images. The API I am using returns a list of objects, each containing an imgUri property which holds the absolute path to the corresponding image stored in a shared folder. ...

Checking radios or checkboxes will always result in a null value when retrieving their form values

After following the instructions in the Angular 2 cookbook for dynamic forms, I encountered an issue with the radios and checkboxes. Despite checking them, they always return a null value. Interestingly, the touched properties of the radios and checkboxes ...

Getting meta values in Angular2 is a common task that can be achieved through

Is there a way to retrieve the meta value from the HTML head in Angular2? For instance, let's say I have the following HTML structure of my project and I want to extract the meta tag with the name "userId". <!doctype html> <html> <he ...

Using jQuery in Jest test with Angular 5: A step-by-step guide

I am facing an issue with my Angular component that utilizes a CalendarService. Upon initialization of the component, I invoke the "calendarService.init()" method. The CalendarService is responsible for configuring a semantic-ui-calendar (which relies on ...

Tips for incorporating nested generics in Typescript

Currently, I am developing a straightforward activity execution framework that allows developers to define activities which can be executed within a workflow. To enhance type safety and boost developer productivity by utilizing type hints, I aim to incorp ...

The Angular/Express application is in search of outdated JavaScript files within the Chrome browser

When updating and deploying my Angular web app on Google App Engine with an Express server, I encounter a peculiar issue. Upon refreshing the browser, I sometimes face a blank page accompanied by the following error: main.f2b54282bab6f51a.js:1 Failed to lo ...

Angular 2 Index HTML loading process for text display

I am a beginner with angular 2. While exploring an angular 2 project created using angular-cli, I came across the following code in the index.html file. However, it seems that the word "Loading" is not being displayed. <app-root>Loading ...</app- ...

Neglectful TypeScript null checks overlooking array.length verification

When TypeScript is compiled with strict null checks, the code snippet below does not pass type checking even though it appears to be correct: const arr: number[] = [1, 2, 3] const f = (n: number) => { } while (arr.length) { f(arr.pop()) } The comp ...

npm encountered an issue when attempting to install a package from a local directory: EISDIR: illegal operation on a directory, read

While attempting to add my compiled TypeScript output as a local package using npm, this error appears: $ npm install --save ../app/out npm ERR! eisdir EISDIR: illegal operation on a directory, read npm ERR! eisdir This is most likely not a problem wit ...

Using Typescript and react-redux with a Stateful Component: The parameter type 'typeof MyClass' does not match the expected component type

I've been trying to dive into the world of Typescript, React, and Redux. However, I've hit a roadblock at the moment. This is the error I encountered: ./src/containers/Hello.tsx [tsl] ERROR in /home/marc/Development/TypeScript-React-Starte ...

Is it necessary for the React generic type prop to be an extension of another type

I have recently started using TypeScript and I am facing a confusion regarding passing generic types into my higher-order component (HOC). My objective is to pass the component props as a generic type in order to have the Component with those specific type ...

Using typescript with Ramda's filter and prop functions can lead to unexpected errors

I'm new to TypeScript and currently facing the challenge of converting JavaScript functions that use Ramda library into TypeScript functions. The lack of clear TypeScript usage in the Ramda documentation is making this task quite difficult for me. Sp ...

Encountering a "args" property undefined error when compiling a .ts file in Visual Studio Code IDE

I've created a tsconfig.json file with the following content: { "compilerOptions": { "target": "es5" } } In my HelloWorld.ts file, I have the following code: function SayHello() { let x = "Hello World!"; alert(x); } However ...

Creating a variable name dynamically using Typescript

I am looking to efficiently create multiple instances of variables and assign values in a single statement, an example of which is shown below. this.myList1[data.id] = data.id + "-" + data.desc; this.myList2[data.id] = data.id + "-" + data.desc; this.myLi ...

Displaying Local Storage Data in Primeng Dropdown

I'm looking to implement local storage for the selected dropdown option, allowing users to see the same selection when they reload the page. Here's my dropdown: <p-dropdown [options]="languages" [(ngModel)]="selectedLanguage ...

What are the reasons for the inability to send form-data in Postman?

Encountering an issue when trying to send form-data in postman as Sequelize returns an error: value cannot be null However, everything works fine when sending a raw request with JSON. Have tried using body-parser and multer, but no luck. This is my inde ...

Encountering a 404 error when using the NestJS GET function within the service and controller

I am facing an issue with creating simple GET logic. When I test it in Postman, I keep receiving a 404 error. books.service.ts contains the following basic logic: constructor( @InjectRepository(Books) private readonly booksRepo: Repository<Boo ...

Exploring the fruitful synergy of Node.js, Mongoose and MongoDB in Typescript for powerful MapReduce operations using the emit() function

Currently, I am experimenting with a side project using the MEAN stack and Typescript. I have encountered an issue where Typescript is not recognizing the typings for the emit() and Array.sum() methods. See my code snippet below... let options: mongoose. ...

What steps should I take to choose esNext from the typescript menu within visual studio 2017?

When utilizing dynamic import with TypeScript in Visual Studio 2017, I encountered the following error: TS1323(TS) Dynamic imports are only supported when the '--module' flag is set to 'commonjs' or 'esNext'. I attempted to c ...