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

使用deepdash的_.filterDeep过滤深层嵌套对象数组时保留父层级

解决方案:用deepdash的_.filterDeep保留完整层级与属性

要实现保留父层级所有属性、仅筛选符合code条件的产品项,关键是正确配置_.filterDeep的核心参数,尤其是clone和childrenPath,以下是具体实现:

1. 先明确数据结构示例

假设你的嵌套数组结构类似这样(不同层级子节点键名可能不同,比如分类用children、产品列表用products):

const products_array = [
  {
    name: "户外装备",
    filter: "season=winter",
    children: [
      {
        name: "保暖系列",
        products: [
          { code: "PUL-001", name: "防风羽绒服", price: 899 },
          { code: "ABC-002", name: "普通棉服", price: 399 }
        ]
      }
    ]
  },
  {
    name: "数码配件",
    filter: "type=charger",
    children: [
      {
        name: "快充系列",
        products: [
          { code: "XYZ-003", name: "65W充电器", price: 129 },
          { code: "PUL-004", name: "便携快充头", price: 79 }
        ]
      }
    ]
  }
];

2. 正确的过滤函数实现

const _ = require('lodash');
require('deepdash')(_);

function filterProductsByCode(productsArray, codeIncludes = 'PUL') {
  return _.filterDeep(productsArray, {
    // 动态识别不同层级的子节点键名(如果所有层级子节点键名一致,直接写字符串如'children'即可)
    childrenPath: (value) => {
      if (Array.isArray(value.children)) return 'children';
      if (Array.isArray(value.products)) return 'products';
      return null;
    },
    clone: true, // 核心:克隆原对象,保留所有属性(而非仅提取匹配路径)
    callback: (value) => {
      // 仅对产品项(含code字段)做匹配判断
      if (value.code && typeof value.code === 'string') {
        return value.code.includes(codeIncludes);
      }
      // 父节点无需返回布尔值,filterDeep会自动保留包含匹配子节点的父层级
    },
    includeRoot: true // 保留根层级数组结构
  });
}

3. 调用与效果

const filteredResult = filterProductsByCode(products_array);
console.log(filteredResult);

输出结果会:

  • 保留所有父节点的name、filter等属性
  • 仅保留code包含'PUL'的产品项,且产品的name、price等属性完整保留
  • 完整维持原有的嵌套层级结构

关键参数说明

  • clone: true:这是解决属性丢失的核心,开启后deepdash会克隆原对象而非仅提取匹配路径,确保所有属性被保留
  • childrenPath:用于告诉工具如何识别各层级的子节点,支持字符串(固定键名)或函数(动态判断)
  • callback逻辑:仅针对目标节点(产品项)返回匹配结果,父节点无需手动判断,工具会自动保留包含有效子节点的父层级

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 04:28:29