0

I have this array of object:

let choices = [
    {title: 'Single Card Payment', func: 'singleCard'},
    {title: 'Monthly Card Payment', func: 'monthlyCard' },
    {title: 'Monthly Direct Debit Payment', func: 'monthlyDD'}
]

I'm looping through with it and I would like to call functions with the value of the func, like this (which is obviously wrong)

for(choice for choices) {
    choice.func('some', 'params');
}
levipadre
  • 569
  • 7
  • 31
  • Use [for...of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) for arrays not [for in](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in). More info in [this post](https://stackoverflow.com/questions/500504/why-is-using-for-in-for-array-iteration-a-bad-idea) – Reyno Feb 22 '22 at 10:53
  • Assuming you have `singleCard` defined in your current scope, changing `func: 'singleCard'` to `func: singleCard` etc. so that it holds a reference to your function should work – Nick Parsons Feb 22 '22 at 10:58

2 Answers2

1

You can create an object with methods. Like below

const funcs = {
    singleCard: () => { console.log('single card called ')}
}

And then call like this

for (i in choices) {
    funcs[choices[i].func]()
}
-3

using evil function:

    let choices = [
    {title: 'Single Card Payment', func: 'singleCard'},
    {title: 'Monthly Card Payment', func: 'monthlyCard' },
    {title: 'Monthly Direct Debit Payment', func: 'monthlyDD'}
]
for(i in choices) {
    eval(choices[i].func)('some', 'params');
}

edit: it's eval guys not evil. 0K.