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

如何在JavaScript中处理特定的对象数组数据结构?

解决对象数组按type合并/添加的需求

基础实现方案

直接利用数组的find方法定位目标对象,再根据结果执行合并或添加操作:

function mergeOrAdd(arr, obj) {
  // 查找数组中type匹配的对象
  const existingObj = arr.find(item => item.type === obj.type);
  
  if (existingObj) {
    // 合并新对象中除type外的属性到已有对象
    const { type, ...rest } = obj;
    Object.assign(existingObj, rest);
  } else {
    // 不存在则添加新对象到数组
    arr.push(obj);
  }
}

// 示例1测试
const arr1 = [
    {type: 1, amount: 100},
    {type: 2, amount: 200},
    {type: 3, amount: 300},
];
const obj1 = {type: 1, name: 'PLN'};
mergeOrAdd(arr1, obj1);
console.log(arr1); // 输出符合示例1预期

// 示例2测试
const arr2 = [
    {type: 1, amount: 100},
    {type: 2, amount: 200},
    {type: 3, amount: 300},
];
const obj2 = {type: 4, amount: 400};
mergeOrAdd(arr2, obj2);
console.log(arr2); // 输出符合示例2预期

大数据量优化方案

如果数组元素较多,使用Map存储type到对象的映射可以将查找时间从O(n)降到O(1),提升性能:

function mergeOrAddOptimized(arr, obj) {
  // 先构建type到对象的映射
  const typeMap = new Map(arr.map(item => [item.type, item]));
  
  if (typeMap.has(obj.type)) {
    const existingObj = typeMap.get(obj.type);
    const { type, ...rest } = obj;
    Object.assign(existingObj, rest);
  } else {
    arr.push(obj);
    typeMap.set(obj.type, obj);
  }
}

说明

  • 合并属性时,Object.assign会覆盖已有对象中同名的非type属性(新值替换旧值),符合常规合并逻辑。
  • 若需保留旧属性不被覆盖,可调整合并逻辑为Object.assign(existingObj, {...existingObj, ...rest}),根据实际需求选择即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 06:09:25