如何基于重复键值重构对象数组 按指定键分组合并数组项
实现方案
核心逻辑是按数组项的type字段做分组聚合,最终映射为要求的结构,不需要引入额外工具库,原生JS即可实现。
处理步骤
- 遍历原始文档数组,以每个文档的
type值作为唯一分组标识,将同类型的文档归集到同一分组下 - 遍历分组结果,将每个分组转换为
{ documentType: 分组类型名, requiredDocs: 分组成员数组 }的结构,最终组装为新的documents数组
代码实现
// 原始输入 const input = { documents: [ { image: 'sample image 1', id_side: 'Front', type: 'Passport' }, { image: 'sample image 2', id_side: 'Back', type: 'Passport' }, { image: 'sample image 3', id_side: 'Back', type: 'License' } ] }; // 分组归集 const typeGroup = new Map(); for (const docItem of input.documents) { const currentType = docItem.type; if (!typeGroup.has(currentType)) { typeGroup.set(currentType, []); } typeGroup.get(currentType).push(docItem); } // 生成目标结构 const output = { documents: Array.from(typeGroup.entries()).map(([documentType, requiredDocs]) => ({ documentType, requiredDocs })) };
说明
- 采用
Map做分组存储,避免普通对象原型链带来的键名冲突问题,遍历性能更优 - 处理过程不会修改原始数组内的对象,仅做引用归集,符合常规数据操作的无副作用要求
- 如果后续需要调整分组规则,比如多字段联合分组,只需要修改分组键的生成逻辑即可,适配性强
内容的提问来源于stack exchange,提问作者DayIsGreen
相关产品推荐
相关产品推荐

