In my init function, I have a loop:
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 actually invoke the functions
this[fruit]()
}
}
}
I am attempting to call functions that meet a specific condition. The functions will be named after the "loop iterator," but I'm struggling to figure out how to dynamically make the call.
apple() { ... }
banana() { ... }
kiwi() { ... }
Therefore, according to the loop's condition, apple()
and kiwi()
should be executed if they are green fruits.
Question: How can I correctly construct the function call within the ngOnInit function?
I have tested:
this[fruit]()
, this.fruit()
, this['fruit']
. Which option is correct?