简体   繁体   中英

How to merge two objects with duplicated key sumup value

I have two objects as follows:

const a = {
  '2021-1': 10,
  '2021-2': 8
}
const b = {
  '2021-1': 10,
  '2020-3': 10,
  '2020-4': 15,
  '2020-5': 12,
  '2020-6': 4
}

I would like to merge two objects and sum up values for duplicated keys.

Expected result is:

{
  '2021-1': 20,
  '2021-2': 8,
  '2020-3': 10,
  '2020-4': 15,
  '2020-5': 12,
  '2020-6': 4
}

You can perform a reduce operation over the entries of the second object to sum the values of each key, using a copy of the first object as the initial value.

 const a = { '2021-1': 10, '2021-2': 8 } const b = { '2021-1': 10, '2020-3': 10, '2020-4': 15, '2020-5': 12, '2020-6': 4 } const res = Object.entries(b).reduce((acc,[k,v])=>{ acc[k] = (acc[k] || 0) + v; return acc; }, {...a}); console.log(res);

This utility function merges the two objects and sums conflicting keys, including all the values unique to either a or b .

 const mergeWithSum = (a, b) => [...Object.keys(a), ...Object.keys(b)].reduce((combined, key) => { combined[key] = (a[key]?? 0) + (b[key]?? 0); return combined; }, {}); const a = { '2021-1': 10, '2021-2': 8 } const b = { '2021-1': 10, '2020-3': 10, '2020-4': 15, '2020-5': 12, '2020-6': 4 } console.log(mergeWithSum(a, b));

here is another solution

function mergeObj(obja, objb) {
    const merged = {...obja};
    for ([key, value] of Object.entries(objb)) {
        if(merged.hasOwnProperty(key)) {
           merged[key] = merged[key] + value
        } else {
           merged[key] = value
        }
    }
    return merged
}

it uses a simple for of loop, from object.entries and we destructure the array that contains key and value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM