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

如何使用Array.reduce()将数组转换为指定结构的分组对象数组

你的代码错误点

  1. 没有给Array.reduce传入初始累加值,默认会拿数组第一个元素作为初始acc,无法实现累加效果
  2. 每次迭代都重新声明空的outputArray,覆盖了之前的累加结果
  3. 缺少按dateOfReport字段分组的逻辑,同日期的多条用户数据没有合并到同一个对象中

正确实现代码

const result = Object.values(
  report.reduce((acc, item) => {
    const curDate = item.dateOfReport
    // 不存在当前日期的分组时先初始化
    if (!acc[curDate]) {
      acc[curDate] = { dateOfReport: curDate }
    }
    // 追加当前用户的指标数据到对应日期分组
    acc[curDate][item.userId] = item.userMetric
    return acc
  }, {}) // 初始值为空白对象,用作日期分组映射表
)

运行上述代码得到的result就是你需要的目标结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 07:45:08