Created
February 12, 2022 22:20
-
-
Save vinkrish/90680dc87a56d6d5443257ec2e87f2c5 to your computer and use it in GitHub Desktop.
NodeJS implementation to generate condition for Query Builder used in frontend. eg: https://github.com/zebzhao/Angular-QueryBuilder, https://github.com/ukrbublik/react-awesome-query-builder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let findAndOrCondition= (obj) => Object.entries(obj).filter(([key, value]) => key === 'condition' && value === 'and' || value === 'or'); | |
const constructCondition = (conditionString, rule_object) => { | |
if(findAndOrCondition(rule_object).length > 0) { | |
conditionString.val += '(' | |
let rules = rule_object.rules | |
console.log('rules', rules) | |
for(var i=0; i<rules.length; i++) { | |
let rule_obj = rules[i] | |
if(findAndOrCondition(rule_obj).length > 0) { | |
constructCondition(conditionString, rule_obj) | |
} else { | |
let condition = `field=${rule_obj.value}` | |
conditionString.val += condition | |
} | |
if(i === rules.length - 1) continue | |
conditionString.val += ` ${rule_object.condition} ` | |
} | |
return conditionString.val += ')' | |
} | |
} | |
let obj = { | |
"condition": "or", | |
"rules": [ | |
{ | |
"condition": "and", | |
"rules": [ | |
{ | |
"field_id": 6, | |
"condition": 2, | |
"value": 300000 | |
}, | |
{ | |
"field_id": 2, | |
"condition": 1, | |
"value": "2021-10-27" | |
} | |
] | |
}, | |
{ | |
"field_id": 6, | |
"condition": 2, | |
"value": 500000 | |
} | |
] | |
} | |
console.log(constructCondition({ val : '' }, obj)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment