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

求助:JavaScript中如何合并两组对象数组?

How to Merge Two Arrays of Objects in JavaScript

Hey there! Let's fix that array merging issue you're having. The problem with Object.assign(a, b) is that it's designed for merging objects, not arrays. Even though arrays are technically objects in JavaScript (with indices as their "keys"), using Object.assign here just overwrites the indices of a with those from b—which is why you only end up with b's values instead of a combined list.

Here are the simplest, most reliable ways to merge your two arrays of objects properly:

1. Spread Operator (Cleanest & Modern Approach)

This creates a brand new array containing all elements from both a and b, without modifying the original arrays:

var a = [{ Id: 1, Name: 'foo' }, { Id: 2, Name: 'boo' }];
var b = [{ Id: 3, Name: 'doo' }, { Id: 4, Name: 'coo' }];

const mergedArray = [...a, ...b];
// Result: [{ Id: 1, Name: 'foo' }, { Id: 2, Name: 'boo' }, { Id: 3, Name: 'doo' }, { Id: 4, Name: 'coo' }]

2. Array.concat() Method

A classic, straightforward approach that also returns a new merged array:

const mergedArray = a.concat(b);
// Same combined result as the spread operator example

3. Modify the Original Array (If You Need To)

If you want to add all elements from b directly into a (instead of creating a new array), use Array.push() with the spread operator:

a.push(...b);
// Now `a` contains all elements from both original arrays

Bonus: Handling Duplicate IDs (For Future Use Cases)

If you ever run into scenarios where your arrays have objects with matching Id values and you need to merge those objects instead of keeping duplicates, you can use a Map to handle this cleanly:

// Example with a duplicate Id in the arrays
var a = [{ Id: 1, Name: 'foo' }, { Id: 2, Name: 'boo' }];
var b = [{ Id: 2, Name: 'updated-boo' }, { Id: 3, Name: 'doo' }];

const idMap = new Map(a.map(item => [item.Id, item]));

b.forEach(item => {
  if (idMap.has(item.Id)) {
    // Merge existing object with new data (preserves existing properties unless overwritten)
    idMap.set(item.Id, { ...idMap.get(item.Id), ...item });
  } else {
    idMap.set(item.Id, item);
  }
});

const mergedUnique = Array.from(idMap.values());
// Result: [{ Id: 1, Name: 'foo' }, { Id: 2, Name: 'updated-boo' }, { Id: 3, Name: 'doo' }]

All these methods work seamlessly with object arrays fetched from your server—no extra hoops needed!

内容的提问来源于stack exchange,提问作者Ismael Bin Azman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 03:52:49