简体   繁体   中英

merge the value of two objects increasing the value of a key if matched [Javascript]

Given two object:

const obj1 = {
  1: 5,
  2: 4
};

const obj2 = {
  1: 10,
  2: 1,
  3: 1
};

How do I merge them with Lodash Merge to create the resulting object of:

const newObj = {
  1: 15,
  2: 5,
  3: 1
};

What have you tried? Nothing because I have no idea how to use merge in this way or if merge is the right way.

Use _.mergeWith() - it has a customizer that enables you to define the how will properties be merged.

 const obj1 = { 1: 5, 2: 4 }; const obj2 = { 1: 10, 2: 1, 3: 1 }; const result = _.mergeWith({}, obj1, obj2, (o1, o2) => { if(_.isNumber(o1)) { return o1 + o2; } }); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> 

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