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

JavaScript中如何合并对象数组内相同属性对应的数组值

Merge Arrays by Matching Keys in an Object Array

Hey folks! Let's solve this problem where we need to combine the arrays associated with identical keys across all objects in an input array. Here's a straightforward, flexible solution:

Step-by-Step Solution

First, let's look at the complete code, then break down how it works:

const a = [ 
  { 26: [0], 27: [100], 28: [0] }, 
  { 26: [0], 27: [100], 28: [0] }, 
  { 26: [0], 27: [100], 28: [0] } 
];

function mergeMatchingKeyArrays(arr) {
  // Use reduce to build our merged object incrementally
  const mergedObj = arr.reduce((accumulator, currentItem) => {
    // Loop through every key in the current object
    Object.keys(currentItem).forEach(key => {
      // Initialize the key's array if it doesn't exist yet
      if (!accumulator[key]) {
        accumulator[key] = [];
      }
      // Append the current key's array to the accumulator's array
      accumulator[key] = accumulator[key].concat(currentItem[key]);
    });
    return accumulator;
  }, {});
  
  // Wrap the merged object in an array as requested
  return [mergedObj];
}

// Test the function
const result = mergeMatchingKeyArrays(a);
console.log(result);
// Output: [{ 26: [0,0,0], 27: [100,100,100], 28: [0,0,0] }]

How It Works

  • Array.reduce(): This method is perfect here because it lets us iterate over the input array and build up a single "accumulator" object that holds our merged arrays. We start with an empty object {} as the initial accumulator.
  • Object.keys().forEach(): For each object in the input array, we loop through all its keys. This ensures we handle every key present, even if some objects have unique keys (the function works seamlessly if your input array has objects with varying keys).
  • Concatenating Arrays: For each key, we check if it exists in the accumulator. If not, we initialize it with an empty array. Then we concatenate the current object's array for that key onto the accumulator's array.
  • Final Wrap: The problem asks for the result to be an array containing the merged object, so we wrap our final mergedObj in square brackets before returning.

Bonus: Handling Edge Cases

If your input array has objects with missing keys (e.g., one object doesn't have key 26), this function will still work—it just won't add any elements to that key's array for the missing object. For example, if one object skips 26, the merged 26 array will only include values from the objects that had that key.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 22:07:38