Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to execute multiple functions from object?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
}}

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading