如何在JavaScript中统计指定年月下对象数组中各名称的attachment数组总长度
解决方案:按指定年月统计attachment总长度
没问题,这完全可以实现!你只需要在原有统计逻辑的基础上,加上时间筛选条件,就能精准统计指定年月的attachment数组总长度。下面是具体的实现步骤和完整代码:
关键思路
- 统一时间格式:把给定的
timeValue("October 2020")转换成便于对比的YYYY-MM格式(比如"2020-10")。 - 筛选符合条件的记录:遍历每个名称的
details时,只统计receivedOn属于目标年月的记录的attachment长度。 - 过滤无有效记录的名称:如果某个名称没有符合条件的记录,就不把它加入最终结果。
完整实现代码
const timeValue = ["October 2020"]; const information = [ {name: 'alpha',details: [ {"attachment": [123, 456], "receivedOn":"2020-10-24 04:05:16.000Z"}, {"attachment": [1454, 1992], "receivedOn":"2020-10-24 04:05:16.000Z"}]}, {name: 'beta',details: [ {"attachment": ["12", 189] , "receivedOn":"2020-10-24 04:05:16.000Z"}, {"attachment": ["maggi", 1890, 2000], "receivedOn":"2021-02-24 04:05:16.000Z"}, {"attachment": [1990, 2001, 2901], "receivedOn":"2020-12-24 04:05:16.000Z"}]}, {name: 'theta',details: [ {"attachment": [1902, 1189] , "receivedOn":"2021-10-24 04:05:16.000Z"}] } ]; // 将目标时间转换为 YYYY-MM 格式,方便后续对比 const targetMonth = new Date(timeValue[0]).toISOString().slice(0, 7); const result = information.reduce((acc, curr) => { let totalLength = 0; // 遍历当前名称的所有详情记录,筛选符合时间条件的条目 curr.details.forEach(detail => { // 提取当前记录的年月部分(YYYY-MM) const recordMonth = detail.receivedOn.slice(0, 7); if (recordMonth === targetMonth) { totalLength += detail.attachment.length; } }); // 只有当存在有效记录时,才将该名称加入结果 if (totalLength > 0) { acc[curr.name] = totalLength; } return acc; }, {}); console.log(result); // 输出:{ alpha: 4, beta: 2 }
简化写法(可选)
如果你更喜欢更简洁的链式调用,可以用filter+reduce组合来替代forEach:
const result = information.reduce((acc, curr) => { const totalLength = curr.details .filter(d => d.receivedOn.slice(0,7) === targetMonth) .reduce((sum, d) => sum + d.attachment.length, 0); if (totalLength) acc[curr.name] = totalLength; return acc; }, {});
这段代码的逻辑和上面完全一致,只是写法更紧凑,你可以根据自己的习惯选择。
内容的提问来源于stack exchange,提问作者Sushant Rad
相关产品推荐
相关产品推荐

