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

103
Views
La mejor manera de reestructurar declaraciones if anidadas

Tengo el siguiente código:

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

¿Hay una forma más limpia de hacer lo anterior? Parece que estoy anidando los estambres if/if y las declaraciones else demasiado y duplicando el código finalArr.push(obj).

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Podrías usar:

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

Sin embargo, creo que su estructura es más fácil de leer.

También puede recorrer Object.values(config) en lugar de las claves, por lo que no necesita el paso adicional de const obj = config[key]; .

about 4 years ago · Santiago Trujillo Report

0

Alternativa:

 if (obj.outlier && !doSomeWithOutlier(obj.outlier)) return; finalArr.push(obj);
about 4 years ago · Santiago Trujillo Report

0

Los otros le mostraron cómo manejar if/if/else como una sola condición para acortar el código, usando Object.values() y .reduce ayudaría a acortar aún más el código:

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

Si desea realizar alguna operación en caso de que .outlier no esté presente, simplemente cambie la última declaración del operador ternario.

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!