_.filter() and new Function in nodejs



这就是我所拥有的,请让我知道如何使用新的Function进程使过滤器通过字典正确过滤。

let _ = require('underscore');
let inventory = [{'id':1, 'color':'red', 'size':'large'}, {'id':2, 'color':'orange', 'size':'small'}, {'id':3, 'color':'orange', 'size':'large'}, {'id':4, 'color':'red', 'size':'small'}, {'id':1, 'color':'orange', 'size':'small'}];
let criteria = 'size==large, id>2';
let data = _.filter(data, new Function(criteria));

该函数只返回"{'id':3, 'color':'orange', 'size':'large'}",而不是任何其他键值对,而是我只是不断得到关于large如何未定义的错误。如果criteria为"id>2",则错误提示2未定义

Function对象需要一组参数和一个函数体。我们能做的是:

let data = _.filter(inventory, new Function('x', 'return x.size === "large" && x.id > 2'));

我也尝试了对象解构,它工作了:

let data = _.filter(inventory, new Function('{size, id}', 'return size === "large" && id > 2'));

虽然这些可以工作,但不建议在代码中使用这样的内容。从MDN:

注意:不建议使用Function构造函数来创建函数,因为它需要函数体作为字符串,这可能会阻止一些JS引擎优化,还可能导致其他问题。

在我看来这样更好:

let data = _.filter(inventory, x => x.size === "large" && x.id > 2);

最新更新