console
const allConfigList = [
{
id: 1,
code: '3',
priority: 1,
type: '111', xxx: '222',
list: [
{ keyName: 'oValue', cond: '>=', keyValue: 9.2, joint: 'OR' },
{ keyName: 'cValue', cond: '>=', keyValue: 19.2, joint: 'OR' }
]
},
{
id: 2,
code: '2',
priority: 3,
type: 'xxx', xxx: '767',
list: [
{ keyName: 'oValue', cond: '>=', keyValue: 9.2, joint: 'AND' },
{ keyName: 'cValue', cond: '!=', keyValue: 15.3, joint: 'OR' },
{ keyName: 'life', cond: '>=', keyValue: 15.3, joint: 'OR' }
]
},
]
const RULE_MAP = {
'AND': '&&',
'OR': '||'
}
function transformOperator(key) {
switch (key) {
case '=':
return '===';
case '!=':
return '!==';
default:
return key;
}
}
function transformInitData() {
const arr = []
for (let i = 0; i < allConfigList.length; i++) {
const item = allConfigList[i]
const obj = Object.assign({}, item)
delete obj.list
const listLen = item.list.length - 1
const cond = item.list.reduce((prev, next, index) => {
prev += `(【${next.keyName}】 ${transformOperator(next.cond)} ${next.keyValue})`
if (index !== listLen) {
prev += ` ${RULE_MAP[next.joint]} `
}
return prev
}, '')
arr.push({
...obj,
operatorString: cond
})
}
return arr
}
function getMatchedTWRuleData(data) {
const arr = transformInitData()
const list = []
for (let i = 0; i < arr.length; i++) {
const item = arr[i]
const reg = /\【(.+?)\】/g
item.operatorString = item.operatorString.replace(reg, function (value) {
const ss = value.replace(/\【/g, '').replace(/\】/g, '')
for (const key in data) {
if (key === ss) {
return data[key]
}
}
})
if (eval(item.operatorString)) {
list.push(item)
}
}
console.table(list)
return list.length ? list.sort((a, b) => a.priority - b.priority < 0 ? -1 : 1)[0] : null
}
const testData = {
id: 12,
all: 212,
oValue: 10,
life: 7.9,
ss: 6.3
}
$(".testData").text(JSON.stringify(testData));
function workCode() {
const res = getMatchedTWRuleData(testData)
console.log('匹配到的结果是=====', res)
$(".strJson").text(JSON.stringify(res));
$(".res").text('匹配到啦!!!')
}
<h4>规则匹配</h4>
<div id="testDiv">
<p>测试数据是:</p>
<div class="testData"></div>
<div>
<br></br>
<button onclick="workCode()">提交</button>
<p>结果是:</p>
<div class="panel-body" style="height:580px;overflow:auto">
<div class="strJson"></div>
<p class="res"></p>
</div>
.res {
color: green;
}