如何使用键从两个对象中获取新的 JavaScript 对象,并在键匹配时对值取平均值

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

比如我有两个对象:

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

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

是否可以从两个对象中获取包含所有键的新对象,并在键匹配时计算两个值的平均值,因此新对象看起来像这样?

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 
 } 

键的值总是 > 0

使用 Object.entries 和 forEach。改变第一个对象。取决于 undefined + n 是 NaN,它是假的,所以 ||将使用第二个值。

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)