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

110
Views
JS Build If (conditions) dynamically according to different array contents

JS

let data1 = [{'id' : '0001', 'area' : 'Paris', 'price' : '100', 'year': '2022'}]
//should construct condition if(id === '0001' && area === 'Paris' && price === '100 && year === '2022')

let data2 = [{'price' : '300', 'year': '2021'}]
//should construct condition if(price === '300' && year === '300')

let data3 = [{'area' : 'Athens'}]
//should construct condition if(area === 'Athens')
// no && when we have only one condition

//my code attempt fo far

let ArrayNew = [];
let operator_and = ' && ';

for(let i = 0; i < data1.length; i++) {
  ArrayNew += data1.map(x => Object.keys(x) + ' === ' + operator_and);
}

console.log('if ('+ ArrayNew +')'); // if (id,area,price,year ===  && )

Question

I am trying to build dynamically conditions inside an if() statement according not only to the number of keys but also to the keys of each given array.

I expect to create something like this

if (generated_conditions) { .... }

almost 4 years ago · Santiago Trujillo
1 answers
Answer question

0

May be try something like this

let data1 = [{'id' : '0001', 'area' : 'Paris', 'price' : '100', 'year': '2022'}]

data1.forEach((item) => {
  let condition = '';
  let keys = Object.keys(item);
  keys.map((k) => {
    if (condition) {
      condition += ` && ${k} == ${item[k]}`
    } else {
      condition = `${k} == ${item[k]}`
    }

  })
  console.log(condition)
})

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