简体   繁体   English

如何从两个 object 中获取新的 JavaScript object 和密钥匹配时的平均值

[英]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?是否有可能获得新的 object 以及来自两个对象的所有键,并在键匹配时计算两个值的平均值,所以新的 object 看起来像这样?

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键的值始终 > 0

Using Object.entries and forEach.使用 Object.entries 和 forEach。 Mutates first object.首先突变 object。 Depends on undefined + n being NaN which is falsy, so ||取决于 undefined + n 是假的 NaN,所以 || 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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