You need to enable JavaScript to run this app. 如何使用lodash的groupBy按月份分组嵌套对象数组生成指定结构?
优惠活动
大模型
产品
解决方案
定价
更多

如何使用lodash的groupBy按月份分组嵌套对象数组生成指定结构?

实现方案

核心逻辑拆解:遍历每一个年度分组,把同月份的活动条目聚合成带label和alldata的结构,最后按月份新旧顺序排序匹配示例输出。

原生JavaScript/TypeScript实现(无第三方依赖)

  • 核心用Map做月份维度的分组,避免依赖库的额外开销
  • 内置月份顺序映射,实现月份的倒序排列(最新月份在前)
// 月份数值映射,用于排序
const monthOrder = {
  Jan: 1, Feb: 2, Mar: 3, Apr: 4, May: 5, Jun: 6,
  Jul: 7, Aug: 8, Sep: 9, Oct: 10, Nov: 11, Dec: 12
};

function transformData(input) {
  return input.map(yearGroup => {
    const monthGroupMap = new Map();
    // 按月份聚合数据
    yearGroup.data.forEach(item => {
      const groupKey = `${item.month} ${item.year}`;
      if (!monthGroupMap.has(groupKey)) {
        monthGroupMap.set(groupKey, []);
      }
      monthGroupMap.get(groupKey).push(item);
    });

    // 转换为要求的结构,按月份倒序排列
    const sortedMonthData = Array.from(monthGroupMap.entries())
      .sort(([labelA], [labelB]) => {
        const monthA = monthOrder[labelA.split(' ')[0]];
        const monthB = monthOrder[labelB.split(' ')[0]];
        return monthB - monthA;
      })
      .map(([label, alldata]) => ({ label, alldata }));

    return {
      year: yearGroup.year,
      data: sortedMonthData
    };
  });
}

Lodash实现

你之前用_.groupBy()没得到预期结构的核心原因是:_.groupBy()的输出是纯键值对对象(格式为{ "Feb 2020": [...], "Jan 2020": [...] }),不是你需要的数组结构,只需要把分组结果做一层格式转换+排序即可:

import _ from 'lodash';

const monthOrder = {
  Jan: 1, Feb: 2, Mar: 3, Apr: 4, May: 5, Jun: 6,
  Jul: 7, Aug: 8, Sep: 9, Oct: 10, Nov: 11, Dec: 12
};

function transformWithLodash(input) {
  return _.map(input, yearGroup => {
    // 按月份+年份做分组
    const groupedResult = _.groupBy(yearGroup.data, item => `${item.month} ${item.year}`);
    // 转换为要求的结构,按月份倒序排列
    const sortedData = _.map(groupedResult, (alldata, label) => ({ label, alldata }))
      .sort((groupA, groupB) => {
        const monthA = monthOrder[groupA.label.split(' ')[0]];
        const monthB = monthOrder[groupB.label.split(' ')[0]];
        return monthB - monthA;
      });

    return {
      year: yearGroup.year,
      data: sortedData
    };
  });
}

注意:上面的实现默认保留同月份下条目的原始输入顺序,如果需要按fulldate时间倒序排列,只需要在分组完成后对alldata数组加一行排序逻辑:
alldata.sort((a, b) => new Date(b.fulldate) - new Date(a.fulldate))


内容的提问来源于stack exchange,提问作者Avdhut

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.29 12:36:08