React Native中如何按周分组API返回的日期数据
按周分组API数据的解决方案
需求说明
从API获取的数据中,每个对象包含createdDate字段,需要按周日至周六为一周的规则分组,例如2022-10-01和2022-10-02属于10月第1周,2022-10-10属于10月第3周。
API响应示例
{ "data": { "fetchOrdersAndRequest": [ { "id": "PI786971", "customerId": [ "C200147" ], "createdDate": "2022-10-01T04:46:00.126Z" }, { "id": "PI786972", "customerId": [ "C200148" ], "createdDate": "2022-10-02T04:46:00.126Z" }, { "id": "PI786972", "customerId": [ "C200149" ], "createdDate": "2022-10-10T04:46:00.126Z" }, { "id": "PI786969", "customerId": [ "C200146" ], "createdDate": "2022-10-24T04:46:00.126Z" }, { "id": "PI786968", "customerId": [ "C200145" ], "createdDate": "2022-10-29T04:46:00.126Z" } ] } }
期望输出格式
{ "period":"lastMonth", "Week":[ { "key":"Week1", "value" : [{ "id": "PI786971", "customerId": [ "C200147" ], "createdDate": "2022-10-01T04:46:00.126Z" }, { "id": "PI786972", "customerId": [ "C200148" ], "createdDate": "2022-10-02T04:46:00.126Z" }], "date": ["2022-10-01","2022-10-02"] }, { "key":"Week2", "value" : [], "date":[] }, { "key":"Week3", "value" : [{ "id": "PI786972", "customerId": [ "C200149" ], "createdDate": "2022-10-10T04:46:00.126Z" }], "date":["2022-10-10"] }, { "key":"Week4", "value" : [], "date":[] }, { "key":"Week5", "value" : [], "date":["2022-10-24","2022-10-29"] }, { "key":"Week6", "value" : [], "date":[] } ] }
现有代码
已实现生成当月周分组的逻辑,但需要将API数据匹配到对应周中:
fetchMonthWeek = ()=>{ var today = new Date(); const month = today.getMonth() + 1 const year = today.getFullYear() var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; let weeks = {} var totalDays = new Date(year, month, 0).getDate(); let weekCount = 1 for (let i = 1; i <= totalDays; i++) { const date = (i < 10 ? '0' + i : i) const fullDate = (year + '-' + (month < 10 ? '0' + month : month) + '-' + date) const currentDay = days[new Date(fullDate).getDay()] if (currentDay === days[0]) weekCount++ const w = 'Week' + weekCount if (weeks[w]) { weeks[w].push(fullDate) } else weeks[w] = [fullDate] } console.log(weeks) let newData = [] for (const w in weeks) { newData.push({ key: w, range: { startDate: weeks[w][0], endDate: weeks[w][weeks[w].length - 1] }, value: weeks[w] }) } return newData }
解决方案代码
以下是整合后的完整代码,实现API数据与周分组的匹配:
// 生成指定年月的周分组结构(周日至周六为一周) const generateMonthWeeks = (year = new Date().getFullYear(), month = new Date().getMonth() + 1) => { const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; let weeks = {}; const totalDays = new Date(year, month, 0).getDate(); let weekCount = 1; // 遍历当月所有日期,按周分组 for (let i = 1; i <= totalDays; i++) { const dateStr = `${year}-${month.toString().padStart(2, '0')}-${i.toString().padStart(2, '0')}`; const currentDay = days[new Date(dateStr).getDay()]; // 遇到周日则周数+1 if (currentDay === days[0]) { weekCount++; } const weekKey = `Week${weekCount}`; if (!weeks[weekKey]) { weeks[weekKey] = []; } weeks[weekKey].push(dateStr); } // 转换为符合基础结构的数组,并初始化value为空数组 return Object.entries(weeks).map(([key, dates]) => ({ key, value: [], date: dates })); }; // 处理API数据,匹配到对应周分组 const groupOrdersByWeek = (apiData, year, month) => { // 生成目标月份的周结构 const weekGroups = generateMonthWeeks(year, month); // 创建日期到周key的映射表,提升查找效率 const dateToWeekMap = {}; weekGroups.forEach(group => { group.date.forEach(date => { dateToWeekMap[date] = group.key; }); }); // 遍历API返回的订单数据,分配到对应周 const orders = apiData.data.fetchOrdersAndRequest; orders.forEach(order => { // 提取createdDate中的日期部分(YYYY-MM-DD) const orderDate = order.createdDate.split('T')[0]; const weekKey = dateToWeekMap[orderDate]; if (weekKey) { const targetGroup = weekGroups.find(group => group.key === weekKey); if (targetGroup) { targetGroup.value.push(order); } } }); // 构造最终输出格式 return { period: "lastMonth", Week: weekGroups }; }; // 示例使用:处理给定的API响应数据(2022年10月) const apiResponse = { "data": { "fetchOrdersAndRequest": [ { "id": "PI786971", "customerId": ["C200147"], "createdDate": "2022-10-01T04:46:00.126Z" }, { "id": "PI786972", "customerId": ["C200148"], "createdDate": "2022-10-02T04:46:00.126Z" }, { "id": "PI786972", "customerId": ["C200149"], "createdDate": "2022-10-10T04:46:00.126Z" }, { "id": "PI786969", "customerId": ["C200146"], "createdDate": "2022-10-24T04:46:00.126Z" }, { "id": "PI786968", "customerId": ["C200145"], "createdDate": "2022-10-29T04:46:00.126Z" } ] } }; const result = groupOrdersByWeek(apiResponse, 2022, 10); console.log(JSON.stringify(result, null, 2));
代码说明
- generateMonthWeeks函数:对原有代码的优化,支持指定年份和月份,生成每个周的基础结构(包含周标识
key、空的订单数组value、该周的所有日期date)。 - dateToWeekMap映射表:建立日期与周标识的对应关系,避免每次查找周分组都遍历数组,提升匹配效率。
- 数据匹配逻辑:遍历每个订单,提取
createdDate中的日期部分,通过映射表找到所属周,将订单加入对应周的value数组。 - 输出构造:按照期望格式包装处理后的周分组数据,
period字段固定为lastMonth。
内容的提问来源于stack exchange,提问作者abhigyan kr
相关产品推荐
相关产品推荐

