题目描述:
对一群学生的所有数值属性(整形或浮点)求均值。要求:
1. 属性名随意变化/增减不影响计算。
2. 属性dict/object任意层级嵌套都可计算(不限于例子的3层)。
3. 结果数据四舍五入,保留2位小数。
输入:
testListWithNestedDicts = [
{
"studentId": 1,
"age": 7,
"height": 2,
"weight": 3,
"scores": {
"spanish": 80,
"mathematics": 90,
"english": 100,
"pe": {
"run": 85,
"jump": 95
}
}
},
{
"studentId": 2,
"age": 8,
"height": 4,
"weight": 6,
"scores": {
"spanish": 90,
"mathematics": 90,
"english": 80,
"pe": {
"run": 90,
"jump": 90
}
}
},
{
"studentId": 3,
"age": 7,
"height": 3,
"weight": 6,
"scores": {
"spanish": 86,
"mathematics": 90,
"english": 75,
"pe": {
"run": 65,
"jump": 90
}
}
}
]
输出:
{
"age": 7.33,
"height": 3.0,
"weight": 5.0,
"scores": {
"spanish": 85.33,
"mathematics": 90.0,
"english": 85.0,
"pe": {
"run": 80.0,
"jump": 91.67
}
}
}
实现代码:
let testListWithNestedDicts = [
{
studentId: 1,
age: 7,
height: 2,
weight: 3,
scores: {
spanish: 80,
mathematics: 90,
english: 100,
pe: {
run: 85,
jump: 95,
},
},
},
{
studentId: 2,
age: 8,
height: 4,
weight: 6,
scores: {
spanish: 90,
mathematics: 90,
english: 80,
pe: {
run: 90,
jump: 90,
},
},
},
{
studentId: 3,
age: 7,
height: 3,
weight: 6,
scores: {
spanish: 86,
mathematics: 90,
english: 75,
pe: {
run: 65,
jump: 90
},
},
},
];
function getValue(val) {
let res = {};
let result;
for (let i = 0; i < val.length; i++) {
result = forEachObj(val[i], res);
}
let obj = {}
getAverage(result, obj);
return obj
}
//取计算结果
function getAverage(res, obj) {
for(let i in res){
if(i=="studentId") continue
if(res[i] instanceof Array){
obj[i] = res[i][2]
}else{
obj[i] = obj[i]||{}
obj[i] = getAverage(res[i],obj[i])
}
}
return obj
}
//遍历求和
function forEachObj(val, res) {
for (let j in val) {
if (typeof val[j] != "object") {
if (j in res) {
res[j][0]++;
res[j][1] += val[j];
res[j][2] = (res[j][1] / res[j][0]).toFixed(2);
} else {
res[j] = [1, val[j]];
}
} else {
res[j] = res[j] || {};
res[j] = forEachObj(val[j], res[j]);
}
}
return res;
}
getValue(testListWithNestedDicts)