我在项目中使用angular2-query-builder。此外,后端项目使用Java,Spring boot和Rulebook作为规则引擎,以触发由angular2-query-builder生成的规则。因此,我需要从angular2-query-builder的输出中做出一个逻辑表达式。
这是由查询生成器生成的类型脚本对象。
var members = [
{ name: "Sue", hobby: ["Swimming", "Running", "Dancing"] },
{ name: "Sam", hobby: ["Cars", "Travelling"] },
{ name: "John", hobby: ["Reading", "Swimming"] },
{ name: "Rob", hobby: ["Running", "Coding"] },
];
var swimmers = members.filter(({hobby}) => hobby.includes('Swimming')).map(({name}) => name);
console.log(swimmers)
我在后端创建的映射模型类:
query = {
condition: 'and',
rules: [
{field: 'age', operator: '<=', value: '16'},
{field: 'gender', operator: '=', value: 'm'}
]
};
我需要从对象中获取RuleSet {
String field;
String value;
String operator;
String entity;
String condition;
RuleSet[] rules;
//...getters and setters}
。
答案 0 :(得分:1)
从ramin,typeScript实现中引用相同的内容
首先将模型定义为:
export class RuleSet {
field? : string;
value? : string | string[] | number;
operator? : string;
entity ?: string;
condition ?: string;
rules ?: RuleSet[];
}
然后定义解码功能:
//params : [{field: 'age', operator: '<=', value: '16'},{field: 'gender', operator:
//'=', value: 'm'}],'and'
decodeQuery(rules : RuleSet[], condition : string) {
for (var i = 0; i < rules.length; i++) {
var item :RuleSet = rules[i];
if (item.rules == null) {
this.expression = this.expression + this.mergeString("(", item.field, item.operator, item.value, ")");
if (i != rules.length - 1) {
this.expression = this.expression + " " + condition + " ";
}
} else {
condition = item.condition;
this.expression = this.expression + "(";
this.decodeQuery(item.rules, condition);
this.expression = this.expression + ")";
}
}
}
mergeString(bracket1,field,operator,value,bracket2) {
var mergedString = bracket1 + " " + field + " " + operator + " " + value + " " + bracket2 ;
return mergedString;
}
称呼它为:
expression : string = "";
this.decodeQuery(query.rules,query.condition);
结果输出如下:
(age <= 16) && (gender = 'm')
答案 1 :(得分:0)
制定一种递归方法以遍历规则
private void decode(RuleSet[] rules, List<String> expressions, String condition) {
for (int i = 0; i < rules.length; i++) {
RuleSet item = rules[i];
if (item.rules == null) {
expressions.add(merge("(", item.field, item.operator, item.value, ")"));
if (i != rules.length - 1) {
expressions.add(condition);
}
} else {
condition = item.getCondition();
expressions.add("(");
decode(item.rules, expressions, condition);
expressions.add(")");
}
}
}
public String merge(String... strings) {
StringBuilder result = new StringBuilder();
for (String item : strings) {
if (item != null) {
result.append(item);
}
}
return result.toString();
}
然后这样称呼它:
List<String> expressions = new ArrayList<>();
decode(querySchema.ruleSet.rules, expressions, querySchema.ruleSet.condition);
通过将表达式的所有项添加到字符串对象中。将会生成逻辑表达式。