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

使用Lodash实现产品对象数组的多条件过滤

使用Lodash实现产品数组的多条件过滤

没问题,我来给你一步步拆解怎么用Lodash搞定这个多条件过滤的需求。首先我们先明确场景:你有一个产品对象数组,需要根据给定的允许分类、颜色(甚至技能等级这类字段)范围来筛选符合条件的产品,用Lodash可以很优雅地实现。

先理清楚输入与需求

假设我们的产品数组是这样的(补全你给出的示例):

const products = [
  { id: 1, name: 'Product 1', category: 'Home', skill: 'Easy', color: 'blue', price: 100.00 },
  { id: 2, name: 'Product 2', category: 'Home', skill: 'Intermediate', color: 'red', price: 120.00 },
  { id: 3, name: 'Product 3', category: 'Office', skill: 'Intermediate', color: 'green', price: 190.00 },
  { id: 4, name: 'Product 4', category: 'Office', skill: 'Advanced', color: 'blue', price: 250.00 }
];

而我们的过滤规则是:只保留分类为Home、颜色是blue或red、技能等级是Easy或Intermediate的产品。

实现步骤与代码示例

1. 基础版:固定条件过滤

用Lodash的_.filter()配合_.includes()和_.isEmpty()来实现:

const _ = require('lodash'); // Node.js环境引入,浏览器直接用<script>引入Lodash即可

// 定义过滤规则:允许的分类、颜色、技能等级
const filterRules = {
  allowedCategories: ['Home'],
  allowedColors: ['blue', 'red'],
  allowedSkills: ['Easy', 'Intermediate']
};

// 执行过滤
const filteredProducts = _.filter(products, (product) => {
  // 分类匹配:如果允许列表为空则跳过检查,否则判断是否在列表内
  const isCategoryMatch = _.isEmpty(filterRules.allowedCategories) || _.includes(filterRules.allowedCategories, product.category);
  // 颜色匹配
  const isColorMatch = _.isEmpty(filterRules.allowedColors) || _.includes(filterRules.allowedColors, product.color);
  // 技能等级匹配
  const isSkillMatch = _.isEmpty(filterRules.allowedSkills) || _.includes(filterRules.allowedSkills, product.skill);

  // 所有条件都满足才保留该产品
  return isCategoryMatch && isColorMatch && isSkillMatch;
});

console.log(filteredProducts);
// 输出结果:Product 1 和 Product 2

2. 进阶版:动态条件过滤

如果以后可能新增更多过滤字段(比如价格范围、库存状态等),可以用_.every()来动态遍历过滤规则,不用每次修改过滤函数:

const dynamicFilterRules = {
  category: ['Home'],
  color: ['blue', 'red'],
  skill: ['Easy', 'Intermediate']
};

const filteredProductsDynamic = _.filter(products, (product) => {
  // 遍历过滤规则的每个键值对,检查产品对应属性是否符合要求
  return _.every(dynamicFilterRules, (allowedValues, field) => {
    return _.isEmpty(allowedValues) || _.includes(allowedValues, product[field]);
  });
});

这个版本的好处是:不管以后要加多少过滤字段,只要在dynamicFilterRules里新增对应的字段和允许值列表,过滤逻辑完全不用改,扩展性拉满。

关键函数说明

  • _.filter():Lodash的核心过滤函数,遍历数组并返回符合判断条件的元素集合
  • _.includes():快速判断某个值是否存在于数组中,比原生Array.includes()兼容性更好(适配旧浏览器)
  • _.isEmpty():用来处理“该条件不做过滤”的场景(比如允许列表为空时,直接跳过这个条件的检查)
  • _.every():用来遍历过滤规则,确保产品的所有指定属性都符合对应规则

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:17:33