如何按月过滤Firestore数据并传入图表的datasets配置项
你的推测是正确的,必须先将Firestore返回的firstDose时间戳转换为JavaScript Date类型,才能进行月份维度的过滤统计,具体实现逻辑如下:
- 首先初始化两个长度为12的数组,分别对应1-12月的第一针、第二针接种量,初始值设为0
- 遍历原始数据,将
firstDose.seconds乘以1000转换为毫秒级时间戳后,传入Date构造函数得到JS日期对象 - 调用日期对象的
getMonth()方法获取月份下标(返回值为0-11,0对应1月,11对应12月),对应下标的接种量计数+1 - 把统计完成的两个数组直接替换到图表
datasets对应的data字段即可
完整可运行代码如下:
export default function App() { const data = [ { doses: { dose2: true, dose1: true, selectedVaccine: "AstraZeneca", firstDose: { seconds: 1630374445, nanoseconds: 511000000 }, }, displayName: "Dark", address: "" }, { address: "", doses: { firstDose: { seconds: 1630135912, nanoseconds: 920000000 }, dose2: true, selectedVaccine: "AstraZeneca", dose1: true }, displayName: "Raven" } ]; // 初始化各月接种数,下标0对应1月,11对应12月 const dose1Count = new Array(12).fill(0); const dose2Count = new Array(12).fill(0); data.forEach(item => { // 转换Firestore时间戳为JS Date const doseDate = new Date(item.doses.firstDose.seconds * 1000); const monthIndex = doseDate.getMonth(); // 统计第一针接种量 if (item.doses.dose1) { dose1Count[monthIndex]++; } // 统计第二针接种量,若第二针有单独时间字段替换firstDose即可 if (item.doses.dose2) { dose2Count[monthIndex]++; } }) return ( <div className="App"> <Line data={{ labels: [ "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月" ], datasets: [ { label: "第一针", data: dose1Count, backgroundColor: ["red"], borderWidth: 1 }, { label: "第二针", data: dose2Count, backgroundColor: ["orange"] } ] }} height={400} width={600} /> </div> ); }
如果需要按指定年份过滤,额外加getFullYear()方法判断年份即可。
内容的提问来源于stack exchange,提问作者JS3
相关产品推荐
相关产品推荐

