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

如何用Lodash按articlenumber合并对象并将详情归入details键

问题根因

你写的合并代码最终得到扁平化结果,核心原因是:Lodash的_.merge是对两个对象 同路径的属性做递归合并,它无法感知你需要将productDetails的内容挂载到details子节点下,只会把两个源的同层级属性直接拼合,最终自然会让color、size字段和name、category平级排布。

注意:从你给出的期望输出(逗号分隔的多个对象结构)可以判断,实际业务场景中products、productDetails都是对象数组,你示例里写的单对象结构只是简化演示。

实现步骤
  • 先用_.keyBy把productDetails转成以articlenumber为键的映射表,省去重复遍历的开销
  • 遍历每一个产品对象,根据自身的articlenumber从映射表中匹配对应的详情数据
  • 把匹配到的详情(剔除冗余的重复articlenumber字段)挂载到产品对象的details键下
可直接运行的代码

数组场景(适配真实业务的多元素结构)

// 构建详情数据的索引映射
const detailMap = _.keyBy(productDetails, 'articlenumber');

// 生成嵌套结构的产品列表
const mergedProducts = _.map(products, product => {
  const matchedDetail = detailMap[product.articlenumber];
  return {
    ...product,
    // 无匹配详情时兜底为空对象,避免出现undefined异常
    details: matchedDetail ? _.omit(matchedDetail, 'articlenumber') : {}
  };
});

单对象简化场景

如果仅需处理单个产品、单个详情的最简场景,可直接通过解构组装,不需要调用合并方法:

const mergedProduct = {
  ...products,
  details: _.omit(productDetails, 'articlenumber')
};
最终输出结构

执行代码后即可得到预期的嵌套效果:

[
  {
    articlenumber: '1',
    name: 'Super Awesome Product',
    category: 'magic',
    details: {
      color: 'red',
      size: 'xxl'
    }
  },
  // 其他匹配到的产品对象
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 15:24:08