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

如何将GraphQL返回的Session数组按date字段分组生成目标结构

实现方案

你需要的按date字段分组的逻辑完全可以用reduce实现,大多数人写不成功通常是漏了最后把中间分组对象转为数组的步骤,具体实现代码如下:

// 模拟你从GraphQL获取的原始数据
const rawSessions = [
  {
    "__typename": "Session",
    "date": "Monday",
    "id": "6180da7e1478f62322df638b",
  },
  {
    "__typename": "Session",
    "date": "Wednesday",
    "id": "6180da7f1478f62322df638c",
  },
  {
    "__typename": "Session",
    "date": "Wednesday",
    "id": "6180da7f1478f62322df638d",
  }
]

// 核心分组逻辑
const groupedSessions = Object.values(
  rawSessions.reduce((accumulator, currentSession) => {
    const currentDate = currentSession.date
    // 首次遇到该日期时初始化分组结构
    if (!accumulator[currentDate]) {
      accumulator[currentDate] = {
        date: currentDate,
        sessions: []
      }
    }
    // 把当前会话项加入对应分组
    accumulator[currentDate].sessions.push(currentSession)
    return accumulator
  }, {})
)

执行后得到的groupedSessions就是你要求的目标结构,默认顺序为原始数组中日期首次出现的顺序。如果需要按日期先后排序,可在上述代码后追加排序逻辑,例如将日期转为时间戳后排序即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:45:07