-2

这是我在输出中得到的 json 数据。我需要获取与它们各自的键对应的所有值的平均值。在这种情况下,我们必须获得 Years 的平均值。

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,

              }
        ]
}
]

};

4

1 回答 1

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
}

将其转换为问题中的格式相当简单。

于 2013-05-31T13:35:00.013 回答