I have an object of functions id, names and parameters.
I want to call the object with an id, that will execute the corresponding function by its string name and passes the associated array parameters.
var funcList = {
"0abc1": {
fn: "myFunc1",
args: ["red", "green"]
},
"1def2": {
fn: "myFunc2",
args: ["blue"]
}
};
const func = funcList["0abc1"];
const funcName = func.fn;
const funcParams = func.args;
window[funcName](funcParams.toString());
When the function has one parameter it works. But doesen’t work with multiple parameters.
Is there a better way to implemented it or correct it ?
Aliou Jalagui is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
If the function has multiple arguments then you can use Spread syntax to pass the array entities to the function individually, instead of as a single string:
var funcList = {
"0abc1": {
fn: "myFunc1",
args: ["red", "green"]
}
}
const func = funcList["0abc1"];
const funcName = func.fn;
const funcParams = func.args;
window[funcName](...funcParams);
function myFunc1(color1, color2) {
console.log(color1);
console.log(color2);
}