You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue中如何从JSON筛选当月numberTerminations并完成计算?

Vue中筛选当月终止数据并计算占比的实现方案

核心思路

  1. 先获取当前月份:通过new Date().getMonth()获取(注意该方法返回0-11的数值,对应1-12月)
  2. 遍历数据时,将每条数据的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 23:18:33