You need to enable JavaScript to run this app. Python中如何按指定key对对象数组进行分组
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何按指定key对对象数组进行分组

方法1:原生JavaScript实现(无第三方依赖)

直接用数组的reduce方法即可实现,代码如下:

const arr = [
  {'grade': 'A', 'name': 'James'},
  {'grade': 'B', 'name': 'Tom'},
  {'grade': 'A', 'name': 'Zelda'}
];

const result = arr.reduce((accumulator, item) => {
  const groupKey = item.grade;
  // 分组不存在时先初始化空数组
  if (!accumulator[groupKey]) {
    accumulator[groupKey] = [];
  }
  accumulator[groupKey].push(item);
  return accumulator;
}, {});

执行完成后result就是你要求的分组结构。

方法2:使用Lodash工具库实现

如果你的项目已经引入了Lodash,直接调用封装好的groupBy方法即可,代码更简洁:

// 已引入Lodash的前提下
const result = _.groupBy(arr, 'grade');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 02:24:04