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

如何将含数组值的对象数组合并为单个对象?

对象数组合并为单对象并合并数组属性的最简实现

这里提供两种场景的最简实现,分别基于原生JavaScript和lodash工具:

原生JavaScript实现

利用数组的reduce方法遍历对象数组,同时遍历每个对象的属性,将对应数组合并到结果对象中:

const before = [
  {
    nodes: [{ "id": "1" }, { "id": "2" }],
    links: [{ "source": "1", "target": "2" }],
  },
  {
    nodes: [{ "id": "3" }, { "id": "4" }, { "id": "5" }, { "id": "6" }],
    links: [{ "source": "3", "target": "4" }, { "source": "5", "target": "6" }],
  }
];

const after = before.reduce((acc, curr) => {
  Object.keys(curr).forEach(key => {
    acc[key] = (acc[key] || []).concat(curr[key]);
  });
  return acc;
}, {});

逻辑说明:

  • 用reduce初始化一个空对象作为累加器
  • 遍历每个对象的属性键,将当前对象的属性数组与累加器中对应属性的数组合并(acc[key] || []处理初始为空的情况)

lodash实现

方法1:使用_.mergeWith自定义合并规则

_.mergeWith支持自定义合并逻辑,针对数组类型直接拼接:

const _ = require('lodash');

const after = _.mergeWith({}, ...before, (objValue, srcValue) => {
  if (Array.isArray(objValue)) {
    return objValue.concat(srcValue);
  }
});

方法2:基于_.flatMap批量处理属性

如果已知所有对象结构一致,还可以先提取属性键,再批量用_.flatMap合并:

const _ = require('lodash');

const attributeKeys = _.keys(before[0]);
const after = _.fromPairs(
  attributeKeys.map(key => [key, _.flatMap(before, key)])
);

这种方式和你提到的单个属性_.flatMap(before, "nodes")思路一致,只是扩展到了所有属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 14:42:50