[英]JavaScript: How to iterate object with two the same keys (and get two values)
[英]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
}
是否有可能获得新的 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
}
键的值始终 > 0
使用 Object.entries 和 forEach。 首先突变 object。 取决于 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.