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

JavaScript如何按指定key对对象数组进行分组重组

实现方案

原代码问题分析

  • 使用map方法做一对一转换,每个原数组元素都会生成一个独立的分类对象,自然出现重复分类
  • 字段引用错误:原对象分类名称字段为obj.category.name,你代码中误写为obj.category.title
  • 调用了不存在的属性:你初始化的数组字段为data,实际push时用了不存在的result.values

正确实现代码

你可以通过reduce做分组聚合,再转换为目标数组格式:

const data = [
  {category: {id: 1, name: 'beverage'}, title: 'Tea'},
  {category: {id: 1, name: 'beverage'}, title: 'Coffee'},
  {category: {id: 2, name: 'snacks'}, title: 'French fries'},
];

// 先以分类id为key做分组聚合
const categoryMap = data.reduce((accumulator, current) => {
  const categoryId = current.category.id;
  // 分类不存在则初始化结构
  if (!accumulator[categoryId]) {
    accumulator[categoryId] = {
      category: current.category.name,
      data: []
    };
  }
  // 推入当前项的title数据
  accumulator[categoryId].data.push({ title: current.title });
  return accumulator;
}, {});

// 将分组映射转换为最终数组
const transformed = Object.values(categoryMap);

运行结果

执行后transformed的输出完全符合预期格式:

[
  {
    category: "beverage",
    data: [ { title: 'Tea' }, { title: 'Coffee' } ]
  },
  {
    category: "snacks",
    data: [ { title: 'French fries' } ]
  }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 15:54:07