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

96
Visualizações
Best way to restructure nested if statements

I have the following code:

const config = {
    key1: {
        outlier: 'outlier1'
    },
    key2: {
        test: 'test'
    },
    key3: {
        outlier: 'outlier3'
    }
}

const finalArr = [];

Object.keys(config).forEach((key) => {
    const obj = config[key];
    // How to make this if/if/else structure cleaner?
    if (obj.outlier) {
        if (doSomeWithOutlier(obj.outlier)) {
            finalArr.push(obj);
        }
    }else {
        finalArr.push(obj);
    }
});

Is there a cleaner way to do the above following? It seems like I am nesting the if/if stamenets and else statements to much and duplicating finalArr.push(obj) code.

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You could use:

    if ((obj.outlier && doSomeWithOutlier(obj.outlier)) || !obj.outlier) {
        finalArr.push(obj);
    }

However, I think your structure is easier to read.

You can also loop over Object.values(config) rather than the keys, so you don't need the extra step of const obj = config[key];.

about 4 years ago · Santiago Trujillo Relatório

0

Alternative:

if (obj.outlier && !doSomeWithOutlier(obj.outlier))
  return;

finalArr.push(obj);
about 4 years ago · Santiago Trujillo Relatório

0

The others showed you how to handle the if/if/else as a single condition to make the code shorter, using Object.values() and .reduce would help to make the code even shorter:

const finalArr = Object.values(config).reduce((arr, el) =>
el.outlier && doSomeWithOutlier(el.outlier) ? [...arr, el] : arr,
[]);

If you want to perform some operation in case .outlier is not present you just change the last statement of ternary operator.

about 4 years ago · Santiago Trujillo 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