我必须在图中显示每日/每周/每月的注册用户数。这是我从后端获取的数据。现在,我需要根据 View 类型遍历数组。
我有这样的数据:
[
{
"date": "2019-10-28",
"count": 0
},
{
"date": "2019-10-29",
"count": 4
},
{
"date": "2019-10-30",
"count": 5
},
{
"date": "2019-10-31",
"count": 2
},
{
"date": "2019-11-01",
"count": 0
},
{
"date": "2019-11-02",
"count": 6
},
{
"date": "2019-11-03",
"count": 0
},
{
"date": "2019-11-04",
"count": 0
},
{
"date": "2019-11-05",
"count": 0
},
{
"date": "2019-11-06",
"count": 0
},
{
"date": "2019-11-07",
"count": 0
},
{
"date": "2019-11-08",
"count": 0
},
{
"date": "2019-11-09",
"count": 0
}
]
如果是每周 View 类型,那么我需要得到如下结果:
[
{
"week": 44,
"count": 15
},
{
"week": 45,
"count": 13
},
{
"week": 46,
"count": 3
},
{
"week": 47,
"count": 13
}
]
如果是蒙特利,那么我需要得到如下结果:
[
{
"10": 100,
"count": 15
},
{
"11": 45,
"count": 13
},
{
"12": 460,
"count": 3
}
]
使用图书馆时刻,我可以获得这样的星期数:
array.forEach((item, index) => {
var weeknumber = moment(item.date).week();
console.log("Week ", weeknumber);
})
我不确定获得所需结果的最佳方法和最佳方法。
有什么建议吗?谢谢!
最佳答案
您需要处理数据并准备通用逻辑以将数据转换为正确的格式。
您可以使用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'))