'Call Javascript functions from variable string name
I am looking for the best method of calling functions with variable names that all follow a specific rule. I am trying to avoid using eval() since there are so many problems about it online.
I have a system setup where different groups have a function that can be called based on their name EG Test group would have a function imported in called getValue_Test(params) and this function can be called for any group name EG getValue_Test2(params) would work if the group name was test2.
I have these functions being imported into the react component and just want to know the best way to call them without making giant switch statement since there will be hundreds of these functions.
Any help would be appreciated :) Thanks
Solution 1:[1]
If you've got some functions defined like this:
function foo() {}
function bar() {}
function baz() {}
You could put them in an object (or map):
const funcs = { foo, bar, baz };
Then you will be able to use a string to access and eventually call the function:
funcs["foo"](); // called foo
const key = "bar";
funcs[key](); // called bar
funcs.baz(); // called baz
However this is usually not recommended. It looks like you might want to use an array instead? Your function names differ only by a number that appears to be incrementing.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | hittingonme |
