Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

190
Views
Call a function according to its string name

I have a code which would be very repetitive, which according to the name of the string of an array executes one function or another.

I give an example of a code as I could do it.

// I use underscore in NodeJS

_.each(refresh, (value, key) => {

    if(key === 'station') {

        station.add({ id: value });

    } else if(key === 'concentrator') {

        concentrator.add({ id: value });
        
    } else if....
});

It is possible to run the function according to your string to avoid so much checking with IF, etc.

[key].add({ id: value });

I have been watching several hours on the internet about the use of call, apply, etc; but I do not understand how it works well, perhaps because my knowledge of Javascript is not advanced.

Thanks !

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Creating an anonymous function on an object is the best approach. As you can use the key to call the method.

Here is an example in code pen: https://codepen.io/liam-hamblin/pen/KKyapNP

The code above takes in the key used to assign the function and does not require any checks. However, it is always the best approach to check that the key exists before calling.

const operations = {};

operations.add = (obj) => {
  document.write("add - ");
  document.write(JSON.stringify(obj));
}

operations.subtract = (obj) => {
  document.write("subtract - ");
  document.write(JSON.stringify(obj));
}

const input = prompt("Enter Function Name, type either subtract or add");

if (operations[input]) {
  operations[input]({id:1});
} else {
  document.write("no matching method")
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!