Vue中如何从JSON筛选当月numberTerminations并完成计算?
Vue中筛选当月终止数据并计算占比的实现方案
核心思路
- 先获取当前月份:通过
new Date().getMonth()获取(注意该方法返回0-11的数值,对应1-12月) - 遍历数据时,将每条数据的
date字段转为Date对象,提取其月份并与当前月份对比,仅保留当月的数据进行计算
修改后的完整代码
created(){ // 获取当前月份(0-11,对应1-12月) const currentMonth = new Date().getMonth(); biService.getBIGraphStatsForCompany() .then(result => { const totalUnits = result.data.totalNumberActiveUnits; // 遍历数据时筛选当月记录 result.data.propertyStatsPerMonth.forEach(field => { // 将字段中的date转为Date对象,提取月份 const dataMonth = new Date(field.date).getMonth(); // 仅处理当月数据 if(dataMonth === currentMonth){ const terminationRate = Math.round(field.numberTerminations / totalUnits * 100); this.chartData.datasets[0].data.push(terminationRate); } }) }) .catch(error => console.error(error)); }
关键细节说明
- 提前缓存
totalNumberActiveUnits,避免每次遍历重复读取,提升性能 - 注意
date字段的格式需能被new Date()正确解析,如果后端返回的是字符串格式(如YYYY-MM-DD),直接传入即可 - 如果需要匹配「当前年份+当月」(避免跨年同月份数据被误选),可以同时对比年份:
const currentYear = new Date().getFullYear(); // ... const dataYear = new Date(field.date).getFullYear(); if(dataMonth === currentMonth && dataYear === currentYear){ // 处理逻辑 }
内容的提问来源于stack exchange,提问作者Maflec
相关产品推荐
相关产品推荐

