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

178
Views
How to remove my nested ternary expressions in my code?

I would like to clean up my code but I can't. I would like to get rid of the nested ternary expressions. I work with react js 17.0.2. Do you have any ideas to help me?

  const buildNewFilters = (query, filtersIndex: Array<string>) => {
    const newFilters = {};
    for (let i = 0; i < filtersIndex.length; i++) {
      newFilters[filtersIndex[i]] = router.query[filtersIndex[i]] ? typeof router.query[filtersIndex[i]] == ('string' || 'number') ? [router.query[filtersIndex[i]]] : router.query[filtersIndex[i]] : undefined
      if (filtersIndex[i] === 'designers' && newFilters.designers) {
        newFilters.designers = newFilters.designers.map(designer => parseInt(designer));
      }
    }
    return newFilters;
  };

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

If you are not used to working with ternary operators, I understand that it's not easy to refactor the code. First, you can read about what ternary expressions are and try them out in the Mozilla Documentation about ternary operators. Basically the part of the code before the ? evaluates to either true or false and if it evaluates to true, the part before the subsequent : is executed (in your case assigned to the variable newFilters[filtersIndex[i]], otherwise the part after the : will be assigned to the variable.

My tip would be to put the line you want to refactor in a text editor to experiment with it, and add line breaks and/or tabs after the ? and : signs to see the structure better and to see what is happening at each step.

about 4 years ago · Juan Pablo Isaza Report

0

if (router.query[filtersIndex[i]]) {
   if (typeof router.query[filtersIndex[i]] == ("string" || "number")) {
     newFilters[filtersIndex[i]] = [router.query[filtersIndex[i]]];
    } else {
      newFilters[filtersIndex[i]] = router.query[filtersIndex[i]];
    }
  } else {
    newFilters[filtersIndex[i]] = undefined;
  }
about 4 years ago · Juan Pablo Isaza 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!