Call a function according to its string name [duplicate]

July 24, 2022, at 02:20 AM
This question already has answers here:
How to execute a JavaScript function when I have its name as a string (35 answers)
Closed 6 months ago.

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 !

Answer 1

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:

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 - ");
operations.subtract = (obj) => {
  document.write("subtract - ");
const input = prompt("Enter Function Name, type either subtract or add");
if (operations[input]) {
} else {
  document.write("no matching method")
Rent Charter Buses Company
Cors not allowed while using Axios

Cors not allowed while using Axios

Hey I was working with fetch a normal fetch to request my API in my server, and It was working, but I found out that Axios is easier, so I tried to replace every fetch, but it looks like xhr doesn't work because of cors,

Unable to rollback parent table record if join table update fails

Unable to rollback parent table record if join table update fails

I've a M:N(many-to-many) relationship between Invoice and Item entities and I'm using sequelize unmanaged transaction to create an invoice by adding items in it

Call webpack-ed function from JS file

Call webpack-ed function from JS file

I'm facing an issue, the goal I want to achieve is call a function from a webpack file