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

如何用ES6将日期对象数组转换为按年聚合的月度数量透视格式数组

方案1:基于你已生成的intermediate中间数据转换

const result = Object.values(
  intermediate.reduce((acc, cur) => {
    const year = Number(cur.year)
    acc[year] ??= { year }
    Object.assign(acc[year], cur)
    return acc
  }, {})
)

如果运行环境不支持空值合并运算符??=,可以替换成普通判断:

const result = Object.values(
  intermediate.reduce((acc, cur) => {
    const year = Number(cur.year)
    if (!acc[year]) acc[year] = { year }
    Object.assign(acc[year], cur)
    return acc
  }, {})
)

方案2:无需中间变量,直接从原data一步转换(更推荐)

const result = Object.values(
  data.reduce((acc, { date, quantity }) => {
    const [month, , year] = date.split('/') // 不需要的day变量可以直接省略占位
    const yearNum = Number(year)
    acc[yearNum] = acc[yearNum] || { year: yearNum }
    acc[yearNum][Number(month)] = quantity
    return acc
  }, {})
)

说明

  • 核心是通过Array.reduce以年份为Key做聚合,把同一年的所有月份数据合并到同一个对象中
  • 最后通过Object.values把聚合后的哈希表转换为你需要的数组格式
  • 所有语法均为ES6标准特性,简洁高效,最终输出的result格式和要求完全一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 14:06:03