You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Lodash按多属性(多值逻辑与)过滤对象集合

通用多条件AND筛选的实现方案

嘿,这个动态多条件AND筛选的需求我之前也碰到过,完全不用手动写死每个字段的逻辑,咱们可以搞个通用的解决方案,不管后续加多少筛选键都能复用。

核心思路

我们可以把筛选条件抽象成一个键值对对象:

  • 键:要筛选的对象属性名(比如color、shape)
  • 值:该属性允许的所有潜在值组成的数组(比如['Red','Orange','Yellow'])

然后利用数组的every()方法实现逻辑AND(所有筛选条件必须同时满足),结合includes()检查对象属性是否在允许值范围内。

具体代码实现

// 示例待筛选对象集合
const items = [
  { id: 1, color: 'Red', shape: 'Circle' },
  { id: 2, color: 'Blue', shape: 'Circle' },
  { id: 3, color: 'Orange', shape: 'Square' },
  { id: 4, color: 'Yellow', shape: 'Circle' },
];

// 你的目标筛选条件:颜色为Red/Orange/Yellow 且 形状为Circle
const targetFilters = {
  color: ['Red', 'Orange', 'Yellow'],
  shape: ['Circle']
};

// 通用筛选函数,支持任意数量的筛选键
const applyFilters = (items, filters) => {
  return items.filter(item => {
    // 遍历所有筛选条件,确保每个条件都满足(逻辑AND)
    return Object.entries(filters).every(([propertyKey, allowedValues]) => {
      // 处理空筛选数组的情况(比如用户没选该条件,直接通过)
      if (allowedValues.length === 0) return true;
      // 检查当前对象的属性是否在允许值列表中
      return allowedValues.includes(item[propertyKey]);
    });
  });
};

// 执行筛选
const filteredItems = applyFilters(items, targetFilters);
console.log(filteredItems);
// 输出结果:[{ id: 1, color: 'Red', shape: 'Circle' }, { id: 4, color: 'Yellow', shape: 'Circle' }]

扩展优化点

  • 处理空筛选条件:如果某个筛选键的允许值数组为空,函数会自动跳过该条件,适合用户没选择该筛选项的场景
  • 处理对象缺失属性:如果部分对象没有某个筛选属性,可以修改判断逻辑,比如return allowedValues.includes(item[propertyKey] ?? '');,让缺失属性的对象直接不匹配
  • 支持复杂类型匹配:如果属性是对象/数组,可以把includes()换成自定义的匹配函数,比如深度比较逻辑

内容的提问来源于stack exchange,提问作者merges

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:14:57