Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

193
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda