Skip to content

Instantly share code, notes, and snippets.

@vinkrish
Created February 12, 2022 22:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vinkrish/90680dc87a56d6d5443257ec2e87f2c5 to your computer and use it in GitHub Desktop.
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
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