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

使用Lodash实现动态嵌套条件的产品数据过滤

实现动态嵌套条件的产品数据过滤(基于Lodash)

我明白你需要根据运行时生成的动态过滤条件,从嵌套结构的产品数据中筛选出符合要求的项。结合你的数据结构,我们可以用Lodash的工具函数来优雅地实现这个逻辑。

核心思路

我们需要完成两个关键步骤:

  • 为每个筛选字段映射到产品数据中的对应嵌套路径
  • 对每个产品,验证它是否满足所有动态筛选条件(每个条件下,产品的对应字段与选中选项存在交集)

完整实现代码

const _ = require('lodash');

// 示例原始产品数据
const productData = [
  {
    "_source": {
      "categories": ["home", "office"],
      "attributes": {
        "colors": ["Red-White-Blue", "Orange-Red-Black"]
      },
      "name": "Product A"
    }
  },
  {
    "_source": {
      "categories": ["public"],
      "attributes": {
        "colors": ["Blue"]
      },
      "name": "Product B"
    }
  },
  {
    "_source": {
      "categories": ["outdoor"],
      "attributes": {
        "colors": ["Green"]
      },
      "name": "Product C"
    }
  }
];

// 示例动态过滤条件
const selectedFilters = {
  categories: ["home", "office", "public"],
  colors: ["Red-White-Blue", "Orange-Red-Black", "Blue"]
};

// 定义筛选字段到产品数据路径的映射
const filterPathMap = {
  categories: "_source.categories",
  colors: "_source.attributes.colors"
};

// 过滤函数
const filterProducts = (products, filters, pathMap) => {
  return _.filter(products, (product) => {
    // 验证所有筛选条件都满足
    return _.every(filters, (selectedOptions, filterKey) => {
      // 安全获取产品对应字段的数组,路径不存在则返回空数组
      const productValues = _.get(product, pathMap[filterKey], []);
      // 检查产品字段与选中选项是否有交集(即至少匹配一个选项)
      return _.intersection(productValues, selectedOptions).length > 0;
    });
  });
};

// 执行过滤
const filteredProducts = filterProducts(productData, selectedFilters, filterPathMap);
console.log(filteredProducts);
// 输出会包含Product A和Product B,Product C不符合条件

代码细节解释

  • 路径映射filterPathMap:把筛选器的键(比如colors)对应到产品数据中的嵌套路径,后续新增筛选字段时,只需添加新的映射关系即可,扩展性极强。
  • _.get函数:安全读取嵌套字段的值,避免因字段不存在导致的报错,默认返回空数组保证后续逻辑正常运行。
  • _.every函数:确保产品满足所有筛选条件(如果业务需要“满足任意一个条件即可”,可以替换为_.some)。
  • _.intersection函数:计算两个数组的交集,只要交集长度大于0,就说明产品符合当前筛选条件。

扩展调整说明

如果你的筛选逻辑需要改为产品必须包含所有选中的选项,只需要把交集判断部分替换为:

// 验证选中的所有选项都存在于产品字段中
return _.every(selectedOptions, option => _.includes(productValues, option));

内容的提问来源于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.26 10:00:16