javascript - 从日期数组中获取每周和每月数据的最佳方法是什么?
问题描述
我必须在图表中显示注册用户的每日/每周/每月计数。这是我从后端获得的数据。现在我需要根据视图类型循环遍历数组。我有这样的数据:
[
{
"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
}
]
如果是每周视图类型,那么我需要得到类似这样的结果:
[
{
"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'))
推荐阅读
- marklogic - 使用 ml-gradle 对 REST API 选项的权限
- c - 读取访问中断:树为 0xAE0A74BF
- node.js - 浏览 Docker 托管的应用程序时出现 ERR_CONNECTION_REFUSED
- r - 不同年份的滚动计数
- python - 在 linux 的 windows 子系统上运行时的 time.clock() 精确规范
- c++ - 我的代码仅适用于一个输入。请指教
- java - Android 在 Cordova 插件中使用自定义依赖项?
- java - 在任何地方解析文本的 XML 文档
- reactjs - ReactJS componentDidUpdate() prevState 等于 currentState
- oracle - 仅使用第一列的多列索引