1 回答

TA貢獻1799條經驗 獲得超8個贊
您需要處理數據并準備通用邏輯以將數據轉換為正確的格式。
您可以使用groupBy并forEach與reduce方法一起準備數據,如下例所示
演示:https ://repl.it/@abhirathore2006/PrepareDataForCharts
const _ = require('lodash');
// use your dataset
let data = [
{
"date": "2019-10-28",
"count": 0
},
{
"date": "2019-10-29",
"count": 4
}
];
// prepare data beforehand to save re-calculations
data.forEach(d=>{
d.dateObj = new Date(d.date)
});
// this method will sum all the counts in given group
function buildData(data, keyName ){
let result = [];
_.forEach(data, (val, key)=>{
let totalCounts = val.reduce((acc, curr)=>{
return acc + curr.count;
}, 0)
result.push({[keyName]:key, count:totalCounts})
})
return result;
}
// this will group data by given output of date method
function groupAndBuild(data, dateMethod, groupKey) {
let groupedData = _.groupBy(data, (d)=>{
return d.dateObj[dateMethod]()
})
return buildData(groupedData, groupKey)
}
// use moment-js or other library to get week number
// and replace dateObj with moment object
console.log(groupAndBuild(data,'getMonth','month'))
添加回答
舉報