这是我输出的json数据。我需要得到与其各自键对应的所有值的平均值。在这种情况下,我们必须得到年份的平均值。
data = {
"Weather": [{
"Calc": [{
"Year": 2003,
"temp": 45,
}, {
"Year": 2005,
"temp": 47,
}, {
"Year": 2008,
"temp": 41,
}
],
}, {
"Calc": [{
"Year": 2003,
"temp": 33,
}, {
"Year": 2005,
"temp": 38,
}, {
"temp": 36,
"Year": 2007,
}
]
}, {
"Calc": [{
"Year": 2004,
"temp": 13,
}, {
"Year": 2005,
"temp": 19,
}, {
"Year": 2008,
"temp": 21,
}
]
}, {
"Calc": [{
"Year": 2003,
"temp": 20,
}, {
"Year": 2005,
"temp": 27,
}, {
"Year": 2008,
"temp": 29,
}
]
}
]
};
现在我需要获取相同键的所有值的均值并将其自定义为此表单 -
data= {
"Weather": [
{
"Calc": [
{
"Year": 2003,
"temp": 45,
},
{
"Year": 2005,
"temp": 47,
},
{
"Year": 2008,
"temp": 41,
}
]
}
]
};
答案 0 :(得分:0)
这是我的方法:
//initialise an empty result object.
var result = {};
//iterate through the weather array.
data.Weather.forEach(function(weather){
//iterate through the contained 'calc' arrays.
weather.Calc.forEach(function(item){
//create a new index in the result object for the given year if it doesn't already exist.
result[item.Year] = result[item.Year] || [];
//add this temperature to the year.
result[item.Year].push(item.temp);
});
});
//we now have an object containing arrays of all the temps under each year
//average them!
for (year in result){
var avg = 0;
result[year].forEach(function(val){
avg += val;
});
avg = avg/result[year].length;
result[year] = avg;
}
console.log(result)
收益:
{
2003: 32.666666666666664,
2004: 13,
2005: 32.75,
2007: 36,
2008: 30.333333333333332
}
转换为问题中的格式非常简单。