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

201
Visualizações
Javascript - shortest way of writing multiple if conditions within forEach loop without writing a separate method

I have below forEach loop

    this.cfData.customAttributes.forEach(function (currentObj) {
        if(currentObj.inputValues !== null) {
          currentObj.inputValues = Array.prototype.map.call(currentObj.inputValues, function(item) { return item.value; }).join(", ");
        }
        if(currentObj.objectType !== null){
          currentObj.objectType = currentObj.objectType.toLowerCase().replace(/(^\w{1})|(\s{1}\w{1})/g, match => match.toUpperCase());
        }
        if(currentObj.dataType !== null){
          currentObj.dataType = currentObj.dataType.toLowerCase().replace(/(^\w{1})|(\s{1}\w{1})/g, match => match.toUpperCase());              
        }
        if(currentObj.isGridEligible !== null){
          currentObj.isGridEligible = currentObj.isGridEligible.toLowerCase().replace(/(^\w{1})|(\s{1}\w{1})/g, match => match.toUpperCase());              
        }
        if(currentObj.isInvoiceEligible !== null){
          currentObj.isInvoiceEligible = currentObj.isInvoiceEligible.toLowerCase().replace(/(^\w{1})|(\s{1}\w{1})/g, match => match.toUpperCase());              
        }
    }); 

I was wondering is there any shortest way of writing these if conditions within the loop? Please suggest.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I will be answering to a more generic code, if you allow me:

  1. First, if you are using single statements, the brackets ({}) around the ifs can be removed.
objArr.forEach(obj => {
    if(obj.propA !== null)
        obj.propA = getPropA(obj);
    
    if(obj.propB !== null)
        obj.propB = getPropB(obj);
    
    ...
}); 
  1. You can always create a way over-complicated code with mapped functions (the getPropA, getPropB and so on).
const getProps = {
    propA(obj){ return ...; },
    propB: obj => ...,
    ...
};

objArr.forEach(obj => {
    // Object.entries receives an object, and returns an array
    //  in the form [ key, value ][]
    for(var [ prop, getter ] of Object.entries(getProps))
        if(obj[prop] !== null)
            obj[prop] = getter(obj);
});
about 4 years ago · Juan Pablo Isaza Relatório

0

I can recommend this code which is way simpler and shorter.

this.cfData.customAttributes.forEach(function (currentObj) {
const arr = ["objectType", "dataType", "isGridEligible", "isInvoiceEligible"];

if (currentObj.inputValues !== null) {
    currentObj.inputValues = Array.prototype.map.call(currentObj.inputValues, function (item) {
        return item.value;
    }).join(", ");
}

arr.forEach(item => {
    if (currentObj[item] !== null) {
        currentObj[item] = currentObj[item].toLowerCase().replace(/(^\w{1})|(\s{1}\w{1})/g, match => match.toUpperCase());
    }
});

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