简体   繁体   中英

How to get the new JavaScript object from two object with the keys and average on values when keys match

For example, I have two objects:

let firstObject = 
 {
   'x' : 3,
   'y' : 2,
   'z' : 1
 }

let secondObject = 
 {
   'x' : 1,
   'y' : 5,
   'c' : 3
 } 

Is it possible to get the new object with all keys from both objects and count average on both values when keys are matched, so the new object would look like this?

newObject = 
 {
   'x' : 2,     // ((3+1)/2)
   'y' : 3.5,   // ((2+5)/2)
   'z' : 1,     // z only in one object, so do nothing and just add to new objects with key : value
   'c' : 3      // c only in one object, so do nothing and just add to new objects with key : value 
 } 

Values of the keys are always > 0

Using Object.entries and forEach. Mutates first object. Depends on undefined + n being NaN which is falsy, so || will use the second value.

 let firstObject = { 'x': 3, 'y': 2, 'z': 1 } let secondObject = { 'x': 1, 'y': 5, 'c': 3 } Object.entries(secondObject).forEach(([k,v])=>firstObject[k]=(firstObject[k]+v)/2||v) console.log(firstObject)

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