【问题标题】:Javascript: How to merge two objects and sum the values of the same key?Javascript:如何合并两个对象并对同一个键的值求和?
【发布时间】:2021-05-04 19:25:54
【问题描述】:
const map1 = { "a": 10, "b": 6 };
const map2 = { "a": 10, "b": 6, "c": 7, "d": 8 };

如果它们具有相同的key,我想合并它们并求和它们的values

const result = { "a": 20, "b": 12, "c": 7, "d": 8 };

如何在不使用任何外部库或++ 的情况下实现这一目标?谢谢!

【问题讨论】:

    标签: javascript object merge


    【解决方案1】:

    使用Array#reduceObject#entries

    const 
      map1 = { "a": 10, "b": 6 },
      map2 = { "a": 10, "b": 6, "c": 7, "d": 8 };
    
    // iterate over map2 entries with acc set to map1 at start
    const merged = Object.entries(map2).reduce((acc, [key, value]) => 
      // if key is already in map1, add the values, otherwise, create new pair
      ({ ...acc, [key]: (acc[key] || 0) + value })
    , { ...map1 });
    
    console.log(merged);

    【讨论】:

    猜你喜欢
    • 2021-12-04
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    • 2013-06-11
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    • 2020-01-19
    相关资源
    最近更新 更多