Reputation: 6158
I'm using this query component in one of my projects so that users can construct a query.
I'm having difficulty parsing it into an actual example query, for example for this object outputted by the component:
const queryParams = {
"rules": [
{
"rules": [
{
"field": "firstName",
"value": "John",
"operator": "="
},
{
"field": "lastName",
"value": "Doe",
"operator": "="
}
],
"combinator": "and"
},
{
"rules": [
{
"field": "age",
"value": "20",
"operator": "="
},
{
"field": "address",
"value": "London",
"operator": "="
}
],
"combinator": "and"
}
],
"combinator": "and"
}
I need to create a function that would output a more user-friendly readable output as such:
((FirstName = John AND LastName = Doe) AND (AGE = 20 AND Address = London))
I've given it a go but the difficulty I'm finding is that:
The object could theoretically be infinitely nested, I never know how nested it is. Is the only way to do this with recursion? Or are there easier ways
The rules and groups can be in the same object
The way I'm currently trying will not work dynamically, so any help or guidance would be greatly appreciated.
Thanks
Upvotes: 2
Views: 61
Reputation: 386634
You could take a recursive approach and build either a rules set or a final comparison.
It works by checking the rules
property:
If given, then the rules
are mapped with a recursive call of the function.
The result of this call is joined with an upper case combinator
property and wrapped into a wanted spaced string with parenthesis.
If not, then take a new string with field
, operator
and value
property.
function combine(object) {
return 'rules' in object
? `(${object.rules.map(combine).join(` ${object.combinator.toUpperCase()} `)})`
: `${object.field} ${object.operator} ${object.value}`;
}
var data = { rules: [{ rules: [{ field: "firstName", value: "John", operator: "=" }, { field: "lastName", value: "Doe", operator: "=" }], combinator: "and" }, { rules: [{ field: "age", value: "20", operator: "=" }, { field: "address", value: "London", operator: "=" }], combinator: "and" }], combinator: "and" },
result = combine(data);
console.log(result);
Upvotes: 3