1

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) { .... }

3
  • 1
    eval comes to mind, but it's generally a bad idea to use eval in most cases. why don't you tell us what you are trying to do with this? there may be a better, simpler solution Commented Sep 21, 2022 at 7:15
  • @nullptr build an if (condition or conditions) according to URL params when and which they exist but I think the general context does not change whatever the case is. For ex. . /search?id=0001 , or /search?id=0001&area=Paris&price=100 , or /search?area=Paris that part is already made, passing the existing URL params into an array (for ex. data1) Commented Sep 21, 2022 at 7:16
  • You can loop over url parameters and do if (data1[urlParam] === urlParamValue) Commented Sep 21, 2022 at 7:22

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.