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

如何优雅实现JavaScript对象合并时重复key值转为数组?

Elegant Way to Merge Objects with Duplicate Keys as Arrays

Great question! Merging objects while combining duplicate keys into arrays is a common need, and using reduce with Object.entries gives us a clean, declarative solution that avoids messy manual loops. Here's how to implement it:

const mergeObjectsWithArrayDuplicates = (...objects) => {
  return objects.reduce((mergedObj, currentObj) => {
    Object.entries(currentObj).forEach(([key, value]) => {
      if (mergedObj.hasOwnProperty(key)) {
        // If the key exists, convert to array if needed and add the new value
        mergedObj[key] = Array.isArray(mergedObj[key]) 
          ? [...mergedObj[key], value] 
          : [mergedObj[key], value];
      } else {
        // Key doesn't exist yet—just assign the value
        mergedObj[key] = value;
      }
    });
    return mergedObj;
  }, {});
};

How It Works

Let’s break down the logic to make it clear:

  • The spread parameter (...objects) lets you pass any number of objects to merge—super flexible for different use cases.
  • reduce builds up our final merged object starting from an empty {}. For each object in the list, we process its key-value pairs.
  • For each key:
    • If it’s already in the merged object, we check if the existing value is an array. If yes, we spread the existing array and append the new value. If not, we wrap both the existing value and new value in a new array.
    • If it’s not in the merged object, we just assign the value directly.

Example Usage (Matching Your Scenario)

let a1 = {key1: 'val1'};
let a2 = {key2: 'val2'};
let b1 = {key1: 'val1b'};

const result = mergeObjectsWithArrayDuplicates(a1, a2, b1);
console.log(result); 
// Output: {key1: ['val1', 'val1b'], key2: 'val2'}

Bonus: Handling Multiple Duplicates

This solution scales seamlessly if you have more than two values for the same key:

let c1 = {key1: 'val1c'};
const extendedResult = mergeObjectsWithArrayDuplicates(a1, b1, c1);
console.log(extendedResult);
// Output: {key1: ['val1', 'val1b', 'val1c']}

Why This Is More Elegant Than Manual Loops

  • It’s declarative: We focus on the end goal (merge objects, combine duplicates into arrays) rather than low-level loop logic.
  • It’s reusable: Drop this function into your codebase and use it anywhere you need this behavior.
  • It’s flexible: Works with 2, 3, or 100 objects—no need to rewrite logic for different numbers of inputs.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:35:30