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) { .... }
CodePudding user response:
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)
})