动态构建表达式以过滤Javascript数组

时间:2017-10-11 14:07:51

标签: javascript arrays boolean-expression

我需要根据另一个数组中的可变数量的项过滤数组。 假设我要过滤的数组如下所示:

var toBeFiltered = [
  {name:"A", parentId: 0},
  {name: "B", parentId: 3},
  {name: "C", parentId: 0},
  {name: "D", parentId: 1},
  ...
]

我需要过滤parentId在另一个数组中的所有元素(例如:var filtering = [3,1,0],但它可以有任何长度)。 如何根据filtering数组的内容动态构建过滤器表达式?在这种情况下,我最终会得到这个表达式:

function(d){return d.parentId == 3 || d.parentId == 1 || d.parentId == 0;}

有没有聪明的方法可以做到这一点?像布尔表达式的连接之类的东西?

2 个答案:

答案 0 :(得分:4)

您可以使用indexOf方法检查给定item中是否存在array

indexOf方法返回指定值的第一次出现,如果找不到-1,则返回value

var toBeFiltered = [
  {name:"A", parentId: 0},
  {name: "B", parentId: 3},
  {name: "C", parentId: 0},
  {name: "D", parentId: 1},
  {name: "E", parentId: 4}
]
var filtering = [3,1,0];
toBeFiltered=toBeFiltered.filter(a=>filtering.indexOf(a.parentId)!==-1);
console.log(toBeFiltered);

您也可以使用Set中的ES6功能。

var toBeFiltered = [
  {name:"A", parentId: 0},
  {name: "B", parentId: 3},
  {name: "C", parentId: 0},
  {name: "D", parentId: 1},
  {name: "E", parentId: 4}
]
var filtering = new Set([3,1,0]);
toBeFiltered=toBeFiltered.filter(a=>filtering.has(a.parentId));
console.log(toBeFiltered);

答案 1 :(得分:2)

您可以Array#includes

var toBeFiltered = [{ name:"A", parentId: 0 }, { name: "B", parentId: 3 }, { name: "C", parentId: 0 }, { name: "D", parentId: 1 }],
    filtering = [1, 0], // to prevent to get the same array as the original
    result = toBeFiltered.filter(o => filtering.includes(o.parentId));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }