I have a loop in an init function:
fruits = {
apple: { color: 'green' },
banana: { color: 'yellow' },
kiwi: { color: 'green' }
}
ngOnInit() {
for ( let fruit in this.fruits ) {
if ( this.fruits[fruit].color === 'green' ) {
// I want to use the current iterator
this[fruit]()
}
}
}
As you can see, I'm trying to make method calls to functions that satisfy the condition. The functions will have the same name as the "loop iterator" - I just can't figure out how to make the call with a dynamic name.
apple() { ... }
banana() { ... }
kiwi() { ... }
So, if you look at the condition in the loop, apple() and kiwi() should be called, assuming they are green fruits.
Question: how do I put together the function call correctly, in the ngOnInit function?
I have tried:
this[fruit]() , this.fruit() , this['fruit'] . What is the correct way?
fruitvariable is an object (judging by it having thecolorproperty) so you're trying to callthis['[object Object]']()or smth like this.fruitwere actually a string than proper way would bethis[fruit]()inoperator, sofruitvariable is a string, so correct way to check its color would beif (fruits[fruit].color === 'green')this[fruit]()doesn't do anything.