遍历嵌套的json并将其自定义为一个新的json
Iterate through nested json and customize it into a new json
这是我在输出中得到的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
}
转换成问题中的格式是相当琐碎的。
相关文章:
- 我可以在json对象中添加一个函数吗
- 根据id将json数组组合为一个json数组
- AngularJS&JSON-从Previous&下一个对象
- 将两个Json提要合并为一个,并按时间排序
- 处理一个JSON文件;完全相同的副本不是
- jquery从2个json字符串构建一个复选框表单
- 如何创建一个包含许多数组和数据的json对象
- 使用javascript或angularjs特定过滤器搜索字符串中第一个img标记的json值
- 为json对象创建一个动态表
- 使用来自不同异步函数的响应创建一个json对象
- 创建一个带有可变字段的json对象
- 想要使用Javascript将一个JSON对象拆分为多个JSON对象
- 如何使用JavaScript forloop从JSON中删除最后一个逗号
- JSON:在另一个JSON对象中重用JSON对象
- 当我JSON.stringfy(对象)时,我得到一个疯狂的字符串作为值
- 我可以使用JS一次使用JSON数组中的一个字符串吗
- 使用transducer-js和most.js创建一个从Json到streams的管道
- 在JSON文件中查找一个元素,并将其显示为HTML
- json 一个 html 的安全方法
- XML 到 JSON 一个项目数组问题