如何实现每周一自动拆分日期数组?含缺失周一的场景处理
按周拆分日期数组(含无数据周的空数组保留)
核心思路
要实现按周一拆分数组且保留无数据周的空数组,关键是先确定当月所有周的范围,提前初始化对应数量的空数组,再将日期数据分配到对应周的数组中。这样即使某周没有符合条件的日期,也会保留空数组。
修改后的完整代码
const mealsRooms = await prisma.users.findUnique({ where: { id: req.params.userId }, select: { MealsRooms: { select: { id: true, servingSabado: true, servingDomingo: true } } } }); const monthFull = req.params.month.split("."); const month = parseInt(monthFull[0]) - 1; // 转换为Date的0-based月份 const year = parseInt(monthFull[1]); const totalDays = new Date(year, month + 1, 0).getDate(); // 获取日期对应的周索引(以周一为周起始,从0开始计数) function getWeekIndex(date) { const firstDayOfMonth = new Date(year, month, 1); let firstMonday = new Date(firstDayOfMonth); const firstDayWeekday = firstDayOfMonth.getDay(); // 计算当月第一个周一的日期 if (firstDayWeekday !== 1) { const daysToAdd = firstDayWeekday === 0 ? 1 : 8 - firstDayWeekday; firstMonday.setDate(firstMonday.getDate() + daysToAdd); } // 当月第一天到第一个周一之间的日期属于第0周 if (date < firstMonday) { return 0; } // 计算当前日期所在的周索引 const daysDiff = Math.floor((date - firstMonday) / (1000 * 60 * 60 * 24)); return Math.floor(daysDiff / 7) + 1; } // 初始化当月所有周的空数组 const lastDay = new Date(year, month, totalDays); const totalWeeks = getWeekIndex(lastDay) + 1; const semanas = Array(totalWeeks).fill().map(() => []); // 查找目标消费区,处理不存在的情况 const mealZone = mealsRooms.MealsRooms.find(room => room.id === req.params.zonaConsumo); if (!mealZone) { return res.status(404).json({ error: "消费区不存在" }); } // 遍历当月每一天,分配到对应周的数组 for (let i = 1; i <= totalDays; i++) { const data = new Date(year, month, i); const weekday = data.getDay(); let shouldAdd = false; // 判断是否需要添加该日期的数据 if (weekday === 6) { shouldAdd = mealZone.servingSabado; } else if (weekday === 0) { shouldAdd = mealZone.servingDomingo; } else { shouldAdd = true; } if (shouldAdd) { const weekIndex = getWeekIndex(data); semanas[weekIndex].push({ date: data.toDateString(), price: 1.46, status: 0, type: "NB", cosumZone: "NB" }); } } res.status(200).json({ listRefeicoes: semanas });
关键修改说明
- 修正Date月份错误:原代码中月份处理未考虑
Date构造函数的0-based特性,现在直接转换为0-based月份,避免日期计算错误。 - 周索引计算:通过
getWeekIndex函数确保每个日期都能对应到正确的周,包括当月第一天到第一个周一之间的日期。 - 提前初始化周数组:先计算当月总周数,创建对应数量的空数组,保证即使某周无数据也会保留空数组。
- 简化逻辑:合并日期添加判断逻辑,用
find替代findIndex查找消费区,同时增加异常处理。
效果验证
修改后返回的listRefeicoes会是一个二维数组,每个子数组对应一周,即使某周没有符合条件的日期,也会保留空数组,完全符合你的期望结构:
{"listRefeicoes":[[第一周数据], [第二周数据], [], [第四周数据], ...]}
内容的提问来源于stack exchange,提问作者Tomás Figueiredo
相关产品推荐
相关产品推荐

