我有一个这样的对象
CalculatorActivity myActivity = (CalculatorActivity)getActivity()
myActivity.setInputValues(fragmentInputValues)
myActivity.doSomethingWithTheValues()
我希望考试年份内的“心理能力”之类的数据应显示为
{
"Mental Ability": [
{
"_id": "1",
"exams": [
{
"_e": "12",
"years": [
{
"y": 2012,
"freq": 3
},
{
"y": 2011,
"freq": 3
}
]
}
]
},
{
"_id": "2",
"exams": [
{
"_e": "12",
"years": [
{
"y": 2011,
"ques_freq": 3
},
{
"y": 2012,
"freq": 1
}
]
}
]
}
]
}
表示应添加并显示同一年的频率 就像2011年的那些考试年一样,应该对频率进行汇总和显示
答案 0 :(得分:0)
我想“ ques_freq”是“ freq”的错字,下面的o是您提到的对象。
function count(mentalAbility) {
let out = {};
mentalAbility.forEach(item => {
item.exams.forEach(exam => {
exam.years.forEach(year => {
out[year.y] === undefined
? (out[year.y] = year.freq)
: (out[year.y] += year.freq);
});
});
});
return out;
}
console.log(count(o['Mental Ability'])); // { '2011': 6, '2012': 4 }
function format(counts) {
return Object.keys(counts).reduce((acc, year) => {
acc.push({
y: year,
freq: counts[year]
});
return acc;
}, []);
}
console.log(format(count(o['Mental Ability']))); // [ { y: '2011', freq: 6 }, { y: '2012', freq: 4 } ]
请注意,我不会为字段查找添加任何未定义/ null检查