The following is JSON is generated from the Search Builder Plugin of Datatables and I would like to display the output in the following format using javascript without use of any library.
(Registration=1)OR((Registration=2)OR(Number=3))OR(Number=4)OR(Station=Yes)
var sbfilter = {
"criteria": [
{
"condition": "=",
"data": "Registration",
"value": [
"1"
]
},
{
"criteria": [
{
"condition": "=",
"data": "Registration",
"value": [
"2"
]
},
{
"condition": "=",
"data": "Number",
"value": [
"3"
]
}
],
"logic": "OR"
},
{
"condition": "=",
"data": "Number",
"value": [
"4"
]
},
{
"condition": "=",
"data": "Station",
"value": [
"Yes"
]
}
],
"logic": "OR"
};
This is what I can think of right now, using a loop and a recursion to go through every nested array and make the query string. The algorithm can be improved.
var sbfilter = { "criteria": [ { "condition": "=", "data": "Registration", "value": [ "1" ] }, { "criteria": [ { "condition": "=", "data": "Registration", "value": [ "2" ] }, { "condition": "=", "data": "Number", "value": [ "3" ] } ], "logic": "OR" }, { "condition": "=", "data": "Number", "value": [ "4" ] }, { "condition": "=", "data": "Station", "value": [ "Yes" ] } ], "logic": "OR" }; var query = ''; function makeQuery(criteria, logic) { criteria.forEach((c, idx, array)=>{ if (c.criteria) { // Add a parentheses since it's the start of a sub query query+='(' makeQuery(c.criteria, c.logic) // Close the parentheses query+=')' } else { query+= '('+c.data+c.condition+c.value[0]+')' } // Check if not the last condition then add the logic to it if (idx.= array.length - 1) { query+=logic } }) } makeQuery(sbfilter,criteria. sbfilter.logic) console.log(query)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.