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

94
Views
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 answers
Answer question

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 Report

0

Alternative:

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

finalArr.push(obj);
about 4 years ago · Santiago Trujillo Report

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 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!