You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular TypeScript环境下使用Lodash实现对象数组格式转换

基于Lodash的Angular TypeScript数组转换通用实现

前置依赖

确保项目已安装Lodash及类型定义:

npm install lodash
npm install @types/lodash --save-dev

通用实现代码

import * as _ from 'lodash';

/**
 * 嵌套数组分组聚合通用工具
 * @param sourceArray 原始输入数组
 * @param nestedChildKey 父级元素中嵌套子数组的键名
 * @param groupKey 分组依据的子元素字段名
 * @param collectConfig 输出字段收集配置,key为输出后的字段名,value指定字段来源路径、是否取自父级
 * @returns 聚合后的结果数组
 */
function transformNestedArray(
  sourceArray: any[],
  nestedChildKey: string,
  groupKey: string,
  collectConfig: Record<string, { path: string; fromParent?: boolean }>
) {
  // 展开嵌套数组,挂载父级元素上下文
  const flattenItems = _.flatMap(sourceArray, parent => 
    _.map(_.get(parent, nestedChildKey), child => ({ ...child, __parentContext: parent }))
  );

  // 按指定字段分组
  const grouped = _.groupBy(flattenItems, groupKey);

  // 聚合每个分组的字段并自动去重
  return _.map(grouped, (groupItems, groupVal) => {
    const res = { [groupKey]: groupVal };
    _.forEach(collectConfig, (conf, outputKey) => {
      const values = _.map(groupItems, item => 
        _.get(conf.fromParent ? item.__parentContext : item, conf.path)
      );
      res[outputKey] = _.uniq(values);
    });
    return res;
  });
}

业务场景调用示例

(注:已修正原输入数据中的语法错误:多余闭合}、ime笔误为Time)

// 你的原始周排班数据
const weekSchedules = [
  {
    dayId: 1,
    daySchedules: [
      { batchScheduleId: 1, Time: '12:00' },
      { batchScheduleId: 1, Time: '12:30' },
      { batchScheduleId: 2, Time: '13:00' },
      { batchScheduleId: 2, Time: '13:30' }
    ]
  },
  {
    dayId: 2,
    daySchedules: [
      { batchScheduleId: 1, Time: '12:00' },
      { batchScheduleId: 1, Time: '12:30' },
      { batchScheduleId: 2, Time: '13:00' },
      { batchScheduleId: 2, Time: '13:30' }
    ]
  }
];

// 调用转换方法,仅需修改配置即可适配其他同类场景
const result = transformNestedArray(
  weekSchedules,
  'daySchedules', // 子数组键名
  'batchScheduleId', // 分组字段
  {
    Time: { path: 'Time' }, // 收集子元素的Time字段
    dayId: { path: 'dayId', fromParent: true } // 收集父元素的dayId字段
  }
);

输出结果完全符合要求:

[
  {
    "batchScheduleId": "1",
    "Time": ["12:00", "12:30"],
    "dayId": [1, 2]
  },
  {
    "batchScheduleId": "2",
    "Time": ["13:00", "13:30"],
    "dayId": [1, 2]
  }
]

复用说明

其他同类转换场景只需修改调用时的后3个参数即可:

  • 修改nestedChildKey适配不同的子数组键名
  • 修改groupKey更换分组依据字段
  • 修改collectConfig自定义要收集的字段、来源路径

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 21:15:04