JavaScript如何从对象数组中按月统计各priority优先级的数量
错误原因
你代码里的问题出在运算符优先级和逻辑判断的写法:&&的优先级低于+,所以(r[key] || 0) + 1 && p2会先完成加法运算得到数字,再和布尔值p2做逻辑与运算,最终返回的结果就是布尔值,这就是你得到true/false的原因。
修复代码
你需要把返回结果的结构调整为每个月份对应一个子对象,子对象内存储各优先级的统计数,修改后的实现如下:
const result = data.reduce((acc, { start_date, priority }) => { const monthKey = start_date.slice(0, 7); // 首次遇到该月份时初始化各优先级计数为0 if (!acc[monthKey]) { acc[monthKey] = { P1: 0, P2: 0, P3: 0 }; } // 对应优先级计数+1 acc[monthKey][priority] += 1; return acc; }, {}); console.log(result);
运行结果
用你提供的测试数据运行后,输出结构如下:
{ "2018-05": { P1: 1, P2: 0, P3: 0 }, "2019-05": { P1: 0, P2: 1, P3: 0 }, "2020-05": { P1: 0, P2: 0, P3: 1 } }
如果你只需要统计P2优先级的数量,不需要其他优先级的统计,可以简化为下面的写法:
const result = data.reduce((acc, { start_date, priority }) => { const monthKey = start_date.slice(0, 7); acc[monthKey] = (acc[monthKey] || 0) + (priority === 'P2' ? 1 : 0); return acc; }, {});
内容的提问来源于stack exchange,提问作者mabo
相关产品推荐
相关产品推荐

