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

使用Lodash将同键关联的子数组对象合并到主数组且不修改原数组

实现方案

实现思路

  • 先使用_.keyBy将子数组转为以Reference字段为键的映射对象,提升匹配效率
  • 遍历父数组时对每个父对象做拷贝,避免修改原始数组内的对象
  • 从映射对象中查找匹配的子对象,追加到拷贝后的父对象的childrenDetail属性中

完整代码

const _ = require('lodash');

const parentDetails = [
    {
        'name': '5003',
        'id': '1'
    },
    {
        'name': '5000',
        'id': '2'
    }
];
const childrenDetails = [
    {
        'cid': '11',
        'Reference': '5003'
    },
    {
        'cid': '22',
        'Reference': '5000'
    }
]; 

// 生成子数据查找映射
const childrenMap = _.keyBy(childrenDetails, 'Reference');

// 生成结果数组,全程不修改原始数据
const result = _.map(parentDetails, parentItem => {
    // 拷贝父对象,避免修改原数据
    const formattedParent = _.cloneDeep(parentItem);
    // 匹配到对应子数据则追加属性
    const matchedChild = childrenMap[parentItem.name];
    if (matchedChild) {
        formattedParent.childrenDetail = _.cloneDeep(matchedChild);
    }
    return formattedParent;
});

可选优化

如果确定父、子对象都是单层基础属性结构,可以把_.cloneDeep换成浅拷贝方法_.clone或者对象展开运算符,减少性能消耗;如果存在一个父对象对应多个子对象的场景,把_.keyBy换成_.groupBy,将childrenDetail改为数组存储即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 17:54:04