例如:
来自
[{
"SchoolYear": 2017,
"Type": "cat 1",
"Count": 7236,
"total": 43864,
"Percentage": 16.50
},
{
"SchoolYear": 2017,
"Type": "cat 2",
"Count": 36628,
"total": 43864,
"Percentage": 83.50
}
]
到
[{
"SchoolYear": 2017,
"cat 1 count": 7236,
"cat 2 count": 36628,
"total": 43864,
"cat 1 Percentage": 16.50,
"cat 2 Percentage": 83.50
}]
答案 0 :(得分:0)
JavaScripts Array.reduce()
非常善于做这样的事情。例如:
const startValues = {
"SchoolYear": 0,
"cat 1 count": 0,
"cat 2 count": 0,
"total": 0,
"cat 1 Percentage": 0,
"cat 2 Percentage": 0
};
const output = input.reduce((result, reportObj) => {
const newCount = result["total"] + reportObj.Count;
const cat1Count = reportObj.type === "cat 1" ? reportObj.Count : 0;
const cat2Count = reportObj.type === "cat 2" ? reportObj.Count : 0;
const cat1Total = result["cat 1 count"] + cat1Count;
const cat2Total = result["cat 2 count"] + cat2Count;
// Not sure what you would want to do if the school year is different?
result["SchoolYear"] = reportObj.SchoolYear;
result["cat 1 count"] += cat1Count;
result["cat 2 count"] += cat2Count;
result["total"] += newCount;
result["cat 1 Percentage"] = cat1Total / result["total"];
result["cat 2 Percentage"] = cat2Total / result["total"];
return result;
}, startValues);