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)