This seems embarrassing to ask, but I'm unsure where to go from here.
I have an array of nested objects and I would like to create a new object that has the average from the original array.
const _ = require(`lodash`)
const data = JSON.parse(`
[
{
"thingOne": {
"numberOne": 1758,
"numberTwo": 97
},
"thingTwo": {
"numberOne": 1758,
"numberTwo": 97
}
},
{
"thingOne": {
"numberOne": 1968,
"numberTwo": 95
},
"thingTwo": {
"numberOne": 2010,
"numberTwo": 95
}
}
]`)
const results = {}
_.each(data, (value, key) => {
_.each(value, (value, key) => {
if (key in results) {
results[key] = {
numberOne: results[key].numberOne + value.numberOne,
numberTwo: results[key].numberTwo + value.numberTwo,
}
} else {
results[key] = value
}
})
})
console.log(results)
I can do this to sum up the array into a new object, but am unsure what to do from here. Do I need to loop this all over again to create an average? Any help appreciated (and I'm not required to use lodash, if there's a simpler answer).
Here's what I'm expected to get in the end:
const expected = {
thingOne: {
numberOne: 1863,
numberTwo: 96,
},
thingTwo: {
numberOne: 1884,
numberTwo: 96,
},
}