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

如何合并两个对象数组:匹配ID合并,保留所有非匹配对象

合并两个对象数组的需求与问题

我需要合并两个对象数组:

const local = [
    {id: 1, balance: 2200, ref: 'A'},
    {id: 2, balance: 2100, ref: 'C'}
]
const remote = [
    {id: 1, balance: 3300, ref: 'B'},
]

合并规则

  • ID相同的对象合并:保留ID,采用remote中的balance值,将两者的ref值合并为text字段(格式为本地ref / 远程ref)
  • ID不匹配的对象直接保留,将原ref字段转为text字段

理想输出

[
    { id: 1, balance: 3300, text: 'A / B' },
    { id: 2, balance: 2100, text: 'C' }
]

我尝试的代码(存在问题)

function mergeFunc(remoteArray, localArray) {
    const newArray = [];
    //loop over one of the arrays
    for (const localObj of localArray) {
        //for each iteration, search for object with matching id in other array
        if(remoteArray.some(remoteObj => remoteObj.id === localObj.id)){
            //if found matching id, fetch this other object
            const id:matchingRemoteObj = remoteArray.find(item => item.id === localObj.id); // 语法错误:变量名定义错误
            //create new, merged, object
            const newObj = {id:matchingRemoteObj.id, balance: id:matchingRemoteObj.balance, text:`${localObj.text} / ${id:matchingRemoteObj.text}`} // 语法错误:balance字段写法错误;字段名错误:原数组是ref不是text
            //push new value to array
            newArray.push(newObj);
        }
    }
    return newArray;
}

这段代码不仅存在语法错误,还只返回了ID匹配的合并对象,没有保留local中ID不匹配的条目,不符合需求。


解决方案

可以通过构建ID映射表高效处理,既能覆盖所有条目,又避免多次遍历数组的性能问题:

function mergeArrays(local, remote) {
    // 先将local数组转为以id为键的Map,同时把ref字段转为text
    const mergedMap = new Map(
        local.map(item => [
            item.id, 
            { id: item.id, balance: item.balance, text: item.ref }
        ])
    );

    // 遍历remote数组处理匹配和新增条目
    remote.forEach(item => {
        if (mergedMap.has(item.id)) {
            // ID匹配:更新balance为remote的值,合并text字段
            const existingItem = mergedMap.get(item.id);
            mergedMap.set(item.id, {
                ...existingItem,
                balance: item.balance,
                text: `${existingItem.text} / ${item.ref}`
            });
        } else {
            // 若remote有local没有的ID,直接添加(不需要可删除此分支)
            mergedMap.set(item.id, {
                id: item.id,
                balance: item.balance,
                text: item.ref
            });
        }
    });

    // 将Map转换为数组返回
    return Array.from(mergedMap.values());
}

// 测试调用
const mergedResult = mergeArrays(local, remote);
console.log(mergedResult);

代码说明

  1. 用Map存储local的所有条目:提前将ref转为text,后续处理更高效
  2. 遍历remote数组:
    • 若ID已存在:更新balance为remote的值,合并text字段
    • 若ID不存在:直接添加到映射中(根据需求可选择保留或忽略remote独有的ID)
  3. 最后将Map的值转为数组,得到包含所有条目且完成合并的结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 18:25:23