如何按部门及子部门分组嵌套数组对象?求实现方案
解决方案:按部门及子部门分组并归集应用
没问题,我来帮你搞定这个分组需求!我猜你之前用reduce的时候可能没处理好部门和子部门的双层匹配逻辑,咱们一步步来调整。
首先先假设你的原始数据结构大概是这样的(如果和你的实际结构有出入,直接调整字段名就行):
const originalData = [ { department: "技术部", sub_department: { name: "前端组", applications: [] }, application: "项目A" }, { department: "技术部", sub_department: { name: "前端组", applications: [] }, application: "项目B" }, { department: "技术部", sub_department: { name: "后端组", applications: [] }, application: "项目C" }, { department: "市场部", sub_department: { name: "品牌组", applications: [] }, application: "项目D" } ];
核心实现逻辑
我们需要用reduce做双层匹配:先匹配外层的部门,再匹配部门下的子部门,最后把对应application归集到子部门的数组里。具体代码如下:
const groupedData = originalData.reduce((acc, item) => { // 1. 查找或创建当前部门分组 let departmentGroup = acc.find(dept => dept.department === item.department); if (!departmentGroup) { departmentGroup = { department: item.department, sub_departments: [] }; acc.push(departmentGroup); } // 2. 查找或创建当前子部门分组 let subDeptGroup = departmentGroup.sub_departments.find(sub => sub.name === item.sub_department.name); if (!subDeptGroup) { // 复制子部门属性并初始化applications数组(避免引用原始数据) subDeptGroup = { ...item.sub_department, applications: [] }; departmentGroup.sub_departments.push(subDeptGroup); } // 3. 将当前application推入对应子部门的数组 subDeptGroup.applications.push(item.application); return acc; }, []);
代码关键点说明
- 外层先判断部门是否已存在,不存在则新建包含
department名称和sub_departments数组的对象 - 内层通过子部门名称匹配,不存在则复制原始子部门的属性(用扩展运算符避免修改原始数据的引用),同时确保
applications数组存在 - 最后把当前项的
application追加到对应子部门的数组中
运行结果示例
执行上面的代码后,groupedData会输出如下结构:
[ { "department": "技术部", "sub_departments": [ { "name": "前端组", "applications": ["项目A", "项目B"] }, { "name": "后端组", "applications": ["项目C"] } ] }, { "department": "市场部", "sub_departments": [ { "name": "品牌组", "applications": ["项目D"] } ] } ]
如果你的原始数据中sub_department本身已经有applications数组且不需要清空,那可以去掉applications: []的初始化,直接用...item.sub_department即可。
内容的提问来源于stack exchange,提问作者user4324324
相关产品推荐
相关产品推荐

