Search code examples
javascriptangularjstypescriptstring-interpolation

How to perform string interpolation in angular/typescript to access value from within a variable?


I have a variable, such as:

demoVars:any[];

which has 3 further properties, var1, var2, var3.

demoArr=[];

Now, in my component class, I have a variable 'selectedVar' which is equal to the name of one of the property; var1, var2, or var3.

Now I want to achieve:

for( const demoVar of this.demoVars)
this.demoArr.push(demoVar.var1);

OR

for( const demoVar of this.demoVars)
this.demoArr.push(demoVar.var2);

OR

for( const demoVar of this.demoVars)
this.demoArr.push(demoVar.var3);

depending on the value of selectedVar.

if i use:

for( const demoVar of this.demoVars)
this.demoArr.push(`demoVar.${this.selectedVar}`);

it pushes the string instead of value;

I want to do something like

for( const demoVar of this.demoVars)
this.demoArr.push(demoVar.`${this.selectedVar}`);

What's the right syntax for this, or what's the right way to do it?


Solution

  • Use bracket notation:

    for( const demoVar of this.demoVars) {
        this.demoArr.push(demoVar[this.selectedVar]);
    }
    

    For extra safety, you can check if object has such property:

    for( const demoVar of this.demoVars) {
        if (demoVar.hasOwnProperty(this.selectedVar)) {
            this.demoArr.push(demoVar[this.selectedVar]);
        }
    }