如何按Key聚合数组对象数据?附示例与错误实现代码
对象数组按字段聚合的实现方案
原始数据
const mockData = [ { id: 1, title: 'Lorem ipsum dolor', assignee: 'Mr First', teams: 'team first', dueDate: 'Monday', status: 'CLOSE', }, { id: 2, title: 'Sit amet', assignee: 'Mr second', teams: 'teams second', dueDate: '10/10/2022', status: 'OPEN', }, ];
目标聚合结构
const aggregated = [ { id: 1, title: 'title', items: [ 'Lorem ipsum dolor', 'Sit amet', ], }, { id: 2, title: 'assignee', items: [ 'Mr First', 'Mr second', ], }, { id: 3, title: 'teams', items: [ 'team first', 'teams second', ], }, // 其他字段的聚合项 ];
原代码问题分析
你当前的reduce实现会生成大量重复元素,原因是每遍历一个数据项的字段,就往结果数组里新增一个对应字段的条目,等于每个字段会被重复添加(数据有N项,每个字段就会生成N个重复条目),完全不符合按字段聚合的需求。
正确实现代码
type ItemType = typeof mockData[0]; type AggregatedItem = { id: number; title: string; items: string[]; }; const aggregated: AggregatedItem[] = Object.values(mockData.reduce((acc: Record<string, Omit<AggregatedItem, 'id'>>, item: ItemType) => { // 遍历当前数据项的所有键值对 Object.entries(item).forEach(([key, value]) => { // 跳过id字段(如果不需要聚合id,可根据需求调整) if (key === 'id') return; // 若当前字段未在聚合容器中,初始化条目 if (!acc[key]) { acc[key] = { title: key, items: [] }; } // 将当前数据项的字段值加入对应条目的items数组 acc[key].items.push(value as string); }); return acc; }, {})).map((item, index) => ({ id: index + 1, // 生成自增的唯一id ...item }));
实现逻辑说明
- 用reduce构建字段映射:通过reduce创建一个以字段名为键的对象,每个键对应一个包含
title(字段名)和items(该字段所有值的数组)的结构,避免重复创建字段条目。 - 过滤不需要的字段:这里跳过了
id字段,如果你需要聚合id,可以删除这个判断。 - 转换为数组并添加id:用
Object.values把映射对象转成数组,再通过map给每个条目添加自增的id。
内容的提问来源于stack exchange,提问作者Jacki
相关产品推荐
相关产品推荐

