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

使用Lodash构建父子关系:合并JSON数组并添加found属性

使用Lodash实现父节点紧随子节点的JSON数组合并

嘿,我来帮你搞定这个需求!咱们要实现的是把父节点数组和子节点数组合并,让每个父节点后面紧跟着它对应的所有子节点,同时给子节点加上found: true属性。下面是具体的实现方案:

实现思路

  1. 先将子节点数组按parent_index字段分组,这样能快速定位每个父节点对应的子节点集合
  2. 遍历父节点数组,对每个父节点,先把它加入结果数组,再将对应的子节点(添加found属性后)追加进去
  3. 利用Lodash的工具方法简化数组处理逻辑

代码实现

// 示例数据
const parentJSON = [
  { index:1, name: 'a'},
  { index:2, name: 'b'},
  { index:3, name: 'c'},
  { index:4, name: 'd'}
];

const childJSON = [
  { index:1, name: 'aa', parent_index:1},
  { index:2, name: 'ab', parent_index:1},
  { index:3, name: 'ba', parent_index: 2},
  { index:4, name: 'bb', parent_index: 2},
  { index:5, name: 'ca', parent_index: 3},
  { index:6, name: 'ad', parent_index: 1}
];

// 使用Lodash处理合并
const _ = require('lodash');

// 按parent_index分组子节点
const groupedChildren = _.groupBy(childJSON, 'parent_index');

// 生成最终结果数组
const mergedResult = _.flatMap(parentJSON, parent => {
  // 获取当前父节点对应的子节点,没有的话返回空数组
  const children = groupedChildren[parent.index] || [];
  // 给子节点添加found属性,然后和父节点组成数组返回
  return [
    parent,
    ..._.map(children, child => ({ ...child, found: true }))
  ];
});

console.log(mergedResult);

输出结果

运行上述代码后,得到的结果和你预期的完全一致:

[
  { index:1, name: 'a'},
  { index:1, name: 'aa', parent_index:1, found: true},
  { index:2, name: 'ab', parent_index:1, found: true},
  { index:6, name: 'ad', parent_index:1, found: true},
  { index:2, name: 'b'},
  { index:3, name: 'ba', parent_index:2, found: true},
  { index:4, name: 'bb', parent_index:2, found: true},
  { index:3, name: 'c'},
  { index:5, name: 'ca', parent_index:3, found: true},
  { index:4, name: 'd'}
]

关键方法说明

  • _.groupBy:高效将子节点按parent_index分组,避免每次查找子节点都遍历整个数组
  • _.flatMap:将每个父节点生成的[父节点, 子节点数组]结构扁平化,直接得到一维结果数组
  • _.map:批量给子节点添加found属性,保持代码简洁

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:17:35