I am trying to iterate an object and display the average for each key inside the object.
Say I have:
data = {
totals: {
item1: {
time: 15,
speed: 20,
amount: 12,
units: 29
},
item2: {
time: 3,
speed: 75,
amount: 14,
units: 3
},
item3: {
time: 19,
speed: 4,
amount: 44,
units: 365
}
}
}
What is the best way to create an average of those values like this:
averages = {
time: 12,
speed: 33,
amount: 40,
units: 132
}
I know to divide the total of each key's value by the total items, but I am struggling to find a good way to iterate each item and add the totals up. The items will be dynamically created depending on the entries for each account.
Is using a for .. in loop the best way? If so how would I use that to accomplish this? something like below?
function findAverage() {
const averages = {
time: 0,
speed: 0,
amount: 0,
units: 0
}
const totalItems = Object.keys(data.totals).length
for (item in data.totals) {
averages.time += item.time;
averages.speed += item.speed;
averages.amount += item.amount;
averages.units += item.units;
}
averages.time = averages.time / totalItems;
averages.speed = averages.speed / totalItems;
averages.amount = averages.amount / totalItems;
averages.units = averages.units / totalItems;
return averages;
}
Is there a better way to go about this problem? Am I totally off in what I am trying to do here?
for (items in data.totals) { for (item in items) { averages[item] += items[item] } }