如何根据查询参数对结果中的月份数据进行排序?
按指定月份顺序重新排列高校统计数据
我已经通过reduce和map方法处理得到了按月份统计的高校数据,但返回结果里每个高校data内的月份字段没有按照查询参数指定的顺序排列。查询参数为from=11(对应Nov)、startYear=2022、end=02(对应Feb)、endYear=2023,需要将data中的月份按Nov→Dec→Jan→Feb的顺序重新排列。
当前得到的数据
"resultArray": [ { "id": 1, "colleges": "NO COLLEGE", "data": { "Dec": 4, "Feb": 3, "Jan": 19, "Nov": 29 } }, { "id": 2, "colleges": "COLLEGE1", "data": { "Dec": 36, "Feb": 45, "Jan": 28, "Nov": 27 } }, { "id": 3, "colleges": "COLLEGE2", "data": { "Dec": 8, "Feb": 62, "Jan": 50, "Nov": 62 } }, ]
现有处理代码
const organizedData = results.reduce((acc, { department, year, month, event_count }) => { acc[department] = acc[department] || {}; acc[department][month] = event_count; return acc; }, {});
const resultArray = Object.keys(organizedData).map((college, idx) => ({ id: idx + 1, colleges: college, data: organizedData[college] }));
解决方案
先定义目标月份顺序的数组,在map阶段针对每个高校的data,按照指定顺序重新构建对象,确保键的顺序符合要求。修改后的代码如下:
// 定义需要的月份顺序 const targetMonthOrder = ['Nov', 'Dec', 'Jan', 'Feb']; const organizedData = results.reduce((acc, { department, year, month, event_count }) => { acc[department] = acc[department] || {}; acc[department][month] = event_count; return acc; }, {}); const resultArray = Object.keys(organizedData).map((college, idx) => { // 按目标顺序重新组装data对象 const orderedData = targetMonthOrder.reduce((acc, month) => { if (organizedData[college][month]) { acc[month] = organizedData[college][month]; } return acc; }, {}); return { id: idx + 1, colleges: college, data: orderedData }; });
处理后期望的数据
"resultArray": [ { "id": 1, "colleges": "NO COLLEGE", "data": { "Nov": 29, "Dec": 4, "Jan": 19, "Feb": 3 } }, { "id": 2, "colleges": "COLLEGE1", "data": { "Nov": 27, "Dec": 36, "Jan": 28, "Feb": 45 } }, { "id": 3, "colleges": "COLLEGE2", "data": { "Nov": 62, "Dec": 8, "Jan": 50, "Feb": 62 } }, ]
内容的提问来源于stack exchange,提问作者Stykgwar
相关产品推荐
相关产品推荐

