3

I have a problem with my application in Angular (with TypeScript language). I need to compare a string data field, such as "string4" with the NAME of an object. Example:

export class MyClass {
  string1: string;
  anyobject: Object;
  string2: string;
  // etc...
}

If I have a method such as:

myMethod(parameter: string) {

}

I want the value inside the parameter match as the name of a data field in my MyClass. For example, is parameter has value "string2", I want to get the string2 value of MyClass (that will be another string).

claudioz
  • 1,121
  • 4
  • 14
  • 25
  • Can't you use switch case? Or may be loop through MyClass variables and get the index of that name. – The Hungry Dictator Sep 08 '17 at 10:16
  • I suggest you go back to your JS tutorial (TypeScript is just a typing layer on top of JavaScript) and review the basic information about objects and how to access their properties. You could start with https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors. –  Sep 08 '17 at 10:48

1 Answers1

0

You can access object properties without the dot notation. For example like this

MyClassObject["value"] and in your case it would be MyClassObject[parameter]

Link to working demo.

FAISAL
  • 33,618
  • 10
  • 97
  • 105
Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
  • Thanks! But I have another problem. MyClassObject[parameter] gives me the correct value, but I can't change the object! If i tried: MyClassObject[parameter] = "newString"; This instruction does not change the instance data field – claudioz Sep 08 '17 at 10:30
  • @claudioz It does change it. Maybe you have the wrong instance. Because that statement is another form of the `.dot` notation. It works the same – Murat Karagöz Sep 08 '17 at 10:33
  • Yes, I wont to assign a new value to the object identified by MyClassObject[parameter] – claudioz Sep 08 '17 at 10:34
  • It finds the correct value (prints the right data field with console.log). But i can't change it with any assignments! – claudioz Sep 08 '17 at 10:39
  • @claudioz You might want to include the code on how you are assigning values to your post or even better open a new question. – Murat Karagöz Sep 08 '17 at 10:42
  • you just need to do `this.MyClassObject[parameter] = 'some new value';` – FAISAL Sep 08 '17 at 10:43