如何修改groupBy函数以按嵌套的type.id对数组分组?
问题需求
需要修改现有的groupBy函数,使其支持按嵌套属性(如type.id)对数组分组,原函数仅能处理顶层属性(如productName、price)。
原函数问题分析
原函数存在以下问题:
- 无法解析嵌套属性路径,直接使用
b[key]会导致嵌套属性(如"type.id")获取失败 - 代码中
push(x)存在变量未定义的错误(应为push(b)) - 返回类型错误:实际返回的是分组对象,而非
T[]类型
修改后的GroupBy函数
static groupBy<T>(data: T[], key: string): Record<string | number, T[]> { // 解析嵌套属性路径,按.分割成数组 const keyParts = key.split('.'); return data.reduce((acc, item) => { // 遍历属性路径,获取最终的分组键值 let currentValue: any = item; for (const part of keyParts) { currentValue = currentValue[part]; // 若属性不存在,提前终止(可根据需求调整处理逻辑) if (currentValue === undefined) break; } // 将当前项加入对应分组 const groupKey = String(currentValue); acc[groupKey] = acc[groupKey] || []; acc[groupKey].push(item); return acc; }, {} as Record<string | number, T[]>); }
关键修改说明
- 嵌套属性解析:通过
split('.')将属性路径拆分为数组,循环遍历获取最终属性值 - 类型修正:返回类型改为
Record<string | number, T[]>,匹配分组对象的结构 - 修复变量错误:将原代码中未定义的
x改为当前遍历项item - 键值处理:将分组键转为字符串,确保数字类型的id(如1、2)能作为对象键正常存储
使用示例
// 按type.id分组 const groupedSales = YourClass.groupBy(sales, "type.id"); console.log(groupedSales);
执行后将得到与预期一致的分组结果:
{ "1": [ { "productName": "AAA", "type": { "id": 1, "name": "Soap" }, "price": 90 }, { "productName": "BBB", "type": { "id": 1, "name": "Soap" }, "price": 85 }, { "productName": "CCC", "type": { "id": 1, "name": "Soap" }, "price": 55 } ], "2": [ { "productName": "DDD", "type": { "id": 2, "name": "shampoo" }, "price": 2 }, { "productName": "EEE", "type": { "id": 2, "name": "shampoo" }, "price": 5 } ] }
内容的提问来源于stack exchange,提问作者BMG
相关产品推荐
相关产品推荐

