Last active
August 10, 2021 01:39
-
-
Save drmcarvalho/954c30d7dad3a9c17ea47dad86c12d57 to your computer and use it in GitHub Desktop.
Mini parse em js
This file contains 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
const regexp = /(\w+?\:|[=><]{1,2}|\S+|\s+(AND|OR)\s+)/g; | |
const input = 'quantity:>10 AND type:(1,2,3) AND group:>=1 AND nome:"Gato"'; | |
const results = input.match(regexp); | |
const data = []; | |
console.log(results); //Debug | |
for (let i = 0, j = results.length; i < j; i++) { | |
const current = results[i].trim(); | |
console.log(current); //debug | |
if (current.indexOf(":") !== -1) { | |
const item = current.split(":"); | |
data.push({ field: item[0], value: item[1] }); | |
} else { | |
data[data.length - 1].sibling = current; | |
} | |
} | |
console.log(JSON.stringify(data, " ", 4)); | |
/* | |
[ | |
{ | |
"field": "quantity", | |
"value": ">10", | |
"sibling": "AND" | |
}, | |
{ | |
"field": "type", | |
"value": "(1,2,3)", | |
"sibling": "AND" | |
}, | |
{ | |
"field": "group", | |
"value": ">=1", | |
"sibling": "AND" | |
}, | |
{ | |
"field": "nome", | |
"value": "\"Gato\"" | |
} | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment