遍历嵌套的json并将其自定义为一个新的json

Iterate through nested json and customize it into a new json

本文关键字:json 一个 自定义 嵌套 遍历      更新时间:2023-09-26

这是我在输出中得到的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,
              }
        ]
}
]

};

这是我的方法:

//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
}

转换成问题中的格式是相当琐碎的。