You have the following interface
export interface Contribuyente {
Campo1: number;
Campo2: string;
Campo3: number;
Campo4: number;
}
And then the following interface is generated
export interface AppState {
Contribuyentes: Contribuyente[];
}
And with this a "class" is generated
export const state: AppState = {
Columnas: [],
Contribuyentes: [
{ Campo1: 1, Campo2: 'N', Campo3: 1, Campo4: 75, },
......
]
}
And now what I want to do is, in a method, obtain the data contained, for example, in Field1, but only receiving the name of Field1 as a parameter.
The trivial solution is given the name of the field, make a big switch and return the corresponding field:
public obtenercampo(campo: string): string {
switch (campo) {
case 'Campo1':
valor = clase.Campo1;
break;
....
}
.....
}
But if the Contributor interface had 30 fields, this model is not pretty.
Is there any other way to access those properties, knowing the name of the field I want to get?
You can use javascript bracket notation. Basically you access the properties of an object, with the name in braces.
An example of use:
If I understand correctly, you have a class and you want to generate a method through which, when passing the name of a field as an argument, it returns the value of that field. Please correct me if I misunderstand what you want.
Your method definition could go like this:
What you return with said function when the field does not exist you vary according to your requirements. If you notice, I have set the value returned by your method to be of type
any
, since the attributes (properties) of your class are of different types.Edition
As @PabloLozano indicates, the statement
return clase[campo]
returnsundefined
if the propertycampo
does not exist in the class. Since I don't know what the requirement is, I put a decision structure so that some other value is returnedundefined
if necessary.