You need to enable JavaScript to run this app. 如何用JavaScript reduce、map将MySQL扁平查询结果转为指定嵌套结构
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript reduce、map将MySQL扁平查询结果转为指定嵌套结构

扁平结果集转层级结构的reduce实现方案

实现思路

基于eventId做一级分组,每个分组节点存储同组共有的shootId值,同时将单行对应的clubEvent条目以clubEventId为键存入分组下的clubEvents对象;整个转换过程通过Array.reduce单次遍历完成,无需多层嵌套循环。

可运行代码

// MySQL查询返回的原始扁平结果集
const flatResultSet = [
    {"eventId":"84","shootId":"72","clubEventId":"253","clubId":"7"},
    {"eventId":"84","shootId":"72","clubEventId":"254","clubId":"5"},
    {"eventId":"84","shootId":"72","clubEventId":"255","clubId":"6"},
    {"eventId":"85","shootId":"72","clubEventId":"256","clubId":"7"},
    {"eventId":"85","shootId":"72","clubEventId":"257","clubId":"5"},
    {"eventId":"85","shootId":"72","clubEventId":"258","clubId":"6"}
];

const transformedResult = flatResultSet.reduce((acc, currentRow) => {
  // 处理原始数据的字符串类型id,匹配目标结构的数值类型要求
  const eventIdKey = currentRow.eventId;
  const shootIdNum = Number(currentRow.shootId);
  const clubEventKey = currentRow.clubEventId;
  const clubEventIdNum = Number(currentRow.clubEventId);
  const clubIdNum = Number(currentRow.clubId);

  // 首次遇到某eventId时,初始化对应分组的基础结构
  if (!acc[eventIdKey]) {
    acc[eventIdKey] = {
      shootId: shootIdNum,
      clubEvents: {}
    };
  }

  // 向当前分组的clubEvents集合中追加当前行对应的条目
  acc[eventIdKey].clubEvents[clubEventKey] = {
    clubEventId: clubEventIdNum,
    clubId: clubIdNum
  };

  return acc;
}, {});

注意:你提供的目标结构中,eventId为85的clubEvents键名存在笔误——按照原始数据的逻辑一致性,该层的键应当使用真实的clubEventId值(即256/257/258),而非重复使用253/254/255。上述代码运行后生成的结构完全匹配合理的层级映射逻辑。

代码运行后的输出结果

{
  "84": {
    "shootId": 72,
    "clubEvents": {
      "253": { "clubEventId": 253, "clubId": 7 },
      "254": { "clubEventId": 254, "clubId": 5 },
      "255": { "clubEventId": 255, "clubId": 6 }
    }
  },
  "85": {
    "shootId": 72,
    "clubEvents": {
      "256": { "clubEventId": 256, "clubId": 7 },
      "257": { "clubEventId": 257, "clubId": 5 },
      "258": { "clubEventId": 258, "clubId": 6 }
    }
  }
}

实现特性

  • 单次遍历完成全量转换,时间复杂度为O(n),处理大结果集时性能稳定
  • 结构映射逻辑和目标层级一一对应,无冗余嵌套,维护成本低
  • 自动完成字符串格式id到数值类型的转换,严格匹配目标结构的类型规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.25 18:54:03