I have an expression like this:
{
"type": "BinaryExpression",
"operator": "OR",
"left": {
"type": "Literal",
"value": 1,
"raw": "1"
},
"right": {
"type": "BinaryExpression",
"operator": "AND",
"left": {
"type": "Literal",
"value": 2,
"raw": "2"
},
"right": {
"type": "Literal",
"value": 3,
"raw": "3"
}
}
}
I want to convert this into the following in JS.
logic: 'OR'
filters: [
{1}
logic: 'AND'
filters: [
{2},
{3}
]
]
i.e. When there is an operator, I will put into a logic variable of the Javascript object. After that, I will check if there is a left and right attribute. If any of them is a literal, I will just add to filters array of javascript object. If the left and the right attribute is a binary expression, then inside the javascript object I would repeat the above process.
I tried various approaches, but somehow I would miss something. So, I am asking here. :
var currentFilter = {
'logic': null,
filters: []
};
test(expression, currentFilter);
function test(expression, currentFilter) {
while (expression.left != null && expression.right != null) {
currentFilter.logic = expression.operator;
if (expression.left.type === 'Literal') {
currentFilter.filters.push = expression.left.value;
} else if (expression.left.type === 'BinaryExpression') {
test(expression.left, currentFilter);
}
if (expression.right.type === 'Literal') {
currentFilter.filters.push = expression.right.value;
} else if (expression.right.type === 'BinaryExpression') {
test(expression.right, currentFilter);
}
}
}