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

如何基于ID从另一数组动态更新数组中的嵌套对象?

如何根据ID深度更新数组中的嵌套对象属性

嘿,这个需求我之前做项目的时候刚好遇到过!你要的是根据ID匹配数组里的对象,然后深度更新嵌套属性——普通的浅合并会直接把整个嵌套对象换掉,而你需要的是只更新嵌套里的特定键,对吧?

我给你整理了一套可行的方案,核心思路是先把更新数据转成ID映射(提升查找效率),再用深度合并处理嵌套属性的更新:

第一步:写一个深度合并工具函数

这个函数会递归处理嵌套对象,只覆盖需要更新的属性,保留原对象里未被修改的内容:

function deepMerge(target, source) {
  // 遍历更新数据的每一个键
  for (const key in source) {
    // 如果当前键对应的值是对象,且原对象也有这个键且值也是对象,就递归合并
    if (source[key] instanceof Object && target[key] instanceof Object) {
      deepMerge(target[key], source[key]);
    } else {
      // 否则直接覆盖原对象的属性值
      target[key] = source[key];
    }
  }
  return target;
}

第二步:处理数组的匹配与更新

接下来我们把更新数据转成ID映射,然后遍历原数组完成更新:

var products = [ 
  { Id: 1, Name: 'Product1', Attributes: { Storage: 'Normal', Size: 'Small' } }, 
  { Id: 2, Name: 'Product2', Attributes: { Storage: 'Normal', Size: 'Small' } } 
];
var newData = [ 
  { Id: 2, Name: 'French Fries' }, 
  { Id: 1, Attributes: { Size: 'Medium' } } 
];

// 把newData转成以Id为键的映射表,快速查找对应更新项
const newDataMap = newData.reduce((map, item) => {
  map[item.Id] = item;
  return map;
}, {});

// 遍历原数组,找到匹配ID的对象并深度更新
products.forEach(product => {
  const updateItem = newDataMap[product.Id];
  if (updateItem) {
    deepMerge(product, updateItem);
  }
});

// 打印结果就是你想要的样子
console.log(products);

效果说明

运行这段代码后,原products数组会被更新成你期望的结果:

[
  { Id: 1, Name: 'Product1', Attributes: { Storage: 'Normal', Size: 'Medium' } },
  { Id: 2, Name: 'French Fries', Attributes: { Storage: 'Normal', Size: 'Small' } }
]

偷懒小技巧

如果你不想自己写deepMerge,可以直接用成熟工具库的方法,比如Lodash的_.merge,用法和我们的自定义函数完全一致:_.merge(product, updateItem),省得自己维护递归逻辑~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:26:12