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

如何使用Lodash按父级Key合并嵌套对象数组?

问题描述

现有如下嵌套对象数组(数组中可包含更多对象):

[
  {
    foo: { something: [{}] },
    bar: { something: [{}] },
    etc: { something: [{}] },
    ...
  },
  {
    foo: { something: [{}] },
    bar: { something: [{}] },
    etc: { something: [{}] },
    ...
  },
];

需要用Lodash按对象的Key合并,让相同Key(比如foo和foo)合并,同时合并something内部的数组内容,期望结果如下:

{
  foo: { something: [{}, {}] },
  bar: { something: [{}, {}] },
  etc: { something: [{}, {}] },
}

注意:something内部可能有重复项,不需要去重;所有Key都是动态的,没法提前指定。

尝试过以下代码但没效果:

// 仅返回每个对象Key为undefined的结果
groupBy(array, (group, key) => group[key])

// 不确定迭代器参数该用什么,返回undefined
groupBy(map(array, (group, key) => group[key]))
解决方案

直接用Lodash的mergeWith就能解决,核心是自定义数组的合并规则——默认merge会用新数组替换旧数组,我们改成把两个数组合并,保留所有元素(包括重复项)。

代码示例:

const _ = require('lodash');

// 你的输入数组
const inputArray = [
  { foo: { something: [{ id: 1 }] }, bar: { something: [{ name: 'a' }] } },
  { foo: { something: [{ id: 2 }, { id: 1 }] }, bar: { something: [{ name: 'b' }] } }
];

// 执行合并
const mergedResult = _.mergeWith({}, ...inputArray, (targetVal, sourceVal) => {
  // 如果合并的是数组,就把源数组内容追加到目标数组后
  if (_.isArray(targetVal)) {
    return targetVal.concat(sourceVal);
  }
  // 非数组的嵌套对象,用Lodash默认的merge逻辑处理
});

console.log(mergedResult);

运行后输出结果:

{
  foo: { something: [ { id: 1 }, { id: 2 }, { id: 1 } ] },
  bar: { something: [ { name: 'a' }, { name: 'b' } ] }
}

为什么这个方法可行?

  • _.mergeWith({}, ...inputArray, customizer):把输入数组里的所有对象依次合并到空对象中,第三个参数是自定义合并函数
  • 自定义函数判断当前合并的是数组时,用concat合并两个数组,保留所有元素(包括重复项)
  • 动态Key的嵌套对象会自动按默认规则合并,不需要提前指定Key

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 05:50:26