I want to call all functions that are located within object.
const data = {
fruits: funcA(),
vegetables: funcB(),
bread: funcC(),
}
Result I want to get is:
firstFunc();
dispatch(funcA());
dispatch(funcB());
dispatch(funcC());
someMoreFunctions();
My code is:
firstFunc();
// I need to somehow execute here all functions from object just like in example above
someMoreFunctions();
I realised it's worth mentioning that I want to pass those functions to child component that will execute them once clicked on:
<Component onClick={()=>{
firstFunc();
// I need to somehow execute here all functions from object just like in example above
someMoreFunctions();
}}
CodePudding user response:
You can iterate through each value of the object, and, if it is a function, call it:
const data = {
fruits: () => console.log('some fruits'),
vegetables: function B() { console.log('more vegetables') },
bread: (function () { return () => console.log('less bread') })(),
pasta: 'No'
}
Object.values(data).forEach(v => typeof(v) == 'function' ? v() : null)
CodePudding user response:
Defining the function:
const object = {
function: () => console.log("You can use functions like this!"),
anotherFunction: log()
}
function log (){
console.log("Yet another way of doing this