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
相关产品推荐
相关产品推荐

