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

求助:如何按type键对字典列表进行分组转换处理

解决字典列表按type分组并重组结构的问题

输入数据

const input = [
  { day: 1, type: "EL", total: 1 },
  { day: 2, type: "EL", total: 3 },
  { day: 1, type: "DL", total: 2 },
  { day: 1, type: "AV", total: 4 },
  { day: 9, type: "CD", total: 2 },
];

解决方案代码

const grouped = {};

input.forEach(item => {
  const { day, type, total } = item;
  if (!grouped[type]) {
    grouped[type] = { type };
  }
  grouped[type][day.toString()] = total;
});

const result = Object.values(grouped);
console.log(result);

代码说明

  1. 临时分组对象:创建grouped对象,用来按type聚合数据,每个键对应一个待生成的目标对象。
  2. 遍历处理每一项:解构出每个元素的day、type、total字段,检查当前type是否已存在于分组对象中,不存在则初始化一个包含type属性的空结构。
  3. 赋值day与total:将day转为字符串作为键,把total赋值给该键,实现按日期存储对应数值。
  4. 转换为目标数组:使用Object.values()提取分组对象的所有值,组成最终的数组结构。

输出结果

[
  { type: "EL", "1": 1, "2": 3 },
  { type: "DL", "1": 2 },
  { type: "AV", "1": 4 },
  { type: "CD", "9": 2 }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 23:10:22