Javascript,使用字符串条件过滤对象列表?

Javascript, filter object list using string condition?

我有这个对象结构:

var objList = [
    { "age": 19, "valueField": 34, "booleanField": false },
    { "age": 15, "valueField": 5,  "booleanField": false },
    { "age": 22, "valueField": 17, "booleanField": true }
];

而这个条件

var condition = 'age > 18 && age < 30 && booleanField == true';

我知道我可以使用一个简单的过滤函数来做到这一点

var newObjList = objList.filter(function(obj) {
    return obj.age > 18 && obj.age < 30 && obj.booleanField == true;
});

但我想使用条件 "as is",而不必在每个字段之前连接 "obj."。像这样

objList.filter(function(obj) {
    return conditon; // all the fields referenced in the condition should point to the corresponding obj fields
})

这可以看作是一个SQL查询

SELECT * 
FROM objlist
where " + condition + ";

这可以做到吗?

注:

我从这个注释开始提到问题的解决方案同时使用了 witheval ,应该非常小心地使用它们(只有当你 保证 condition 字符串不会包含恶意代码).

解法:

您可以使用 evalwith 来达到这样的目的:

var newObjList = objList.filter(function(obj) {
    return eval("with(obj) {" + condition + "}");
});

示例:

var objList = [ { "age": 19, "valueField": 34, "booleanField": false }, { "age": 15, "valueField": 5,  "booleanField": false }, { "age": 22, "valueField": 17, "booleanField": true } ];
var condition = 'age > 18 && age < 30 && booleanField == true';

var newObjList = objList.filter(function(obj) {
    return eval("with(obj) {" + condition + "}");
});

console.log(newObjList);

您可以用对象后缀替换 condition 中对象的所有已知键,并生成一个新函数作为具有替换条件和 return 语句的回调。

也许您需要填充替换键以防止替换不需要的子字符串。

var array = [{ age: 19, valueField: 34, booleanField: false }, { age: 15, valueField: 5, booleanField: false }, { age: 22, valueField: 17, booleanField: true }];
    condition = 'age > 18 && age < 30 && booleanField == true',
    cb = new Function('o', 'return ' + condition.replace(new RegExp(Object.keys(array[0]).join('|'), 'g'), 'o.$&'));

console.log(array.filter(cb));