【js】两个数组对象合并成一个树结构的数据

 1  模板
 2  /**
 3   * 合并两个数组,将岗位信息按照部门进行分组
 4   * @param {Array} array1 岗位信息数组,每个岗位包含部门ID(deptId)、岗位ID(postId)和岗位名称(postName)
 5   * @param {Array} array2 部门信息数组,每个部门包含部门ID(id)和部门名称(label)
 6   * @returns {Array} 返回一个新数组,每个元素代表一个部门,包含部门ID、部门名称和该部门下的所有岗位(children)
 7   */
 8  mergeArrays(array1, array2) {
 9      const result = []
10      // 遍历部门信息数组,为每个部门创建一个岗位子数组
11      array2.forEach(item => {
12          // 初始化岗位子数组
13          const children = []
14          // 遍历岗位信息数组,将属于当前部门的岗位添加到岗位子数组中
15          array1.forEach(post => {
16              if (post.deptId === item.id) {
17                  children.push({
18                      deptId: post.deptId,
19                      id: post.postId,
20                      deptName: post.deptName,
21                      label: post.postName
22                  })
23              }
24          })
25          // 将部门及其岗位子数组添加到结果数组中
26          result.push({
27              id: item.id,
28              label: item.label,
29              children: children
30          })
31      })
32 
33      return result
34  }

这是一个通用的两个数组对象合并为一个树结构数组的方法,其中的参数可以根据自己的需求进行修改:以下是测试数据,可以自行设置查看返回数据:

 1  const array1 = [{
 2          deptId: 1,
 3          postId: 1,
 4          deptName: 'Department A',
 5          postName: 'Position A'
 6      },
 7      {
 8          deptId: 1,
 9          postId: 2,
10          deptName: 'Department A',
11          postName: 'Position B'
12      },
13      {
14          deptId: 2,
15          postId: 3,
16          deptName: 'Department B',
17          postName: 'Position C'
18      }
19  ]
20  const array2 = [{
21          id: 1,
22          label: 'Department A'
23      },
24      {
25          id: 2,
26          label: 'Department B'
27      }
28  ]

 

posted @ 2024-04-22 09:18  狂扇赵四那半拉好嘴  阅读(113)  评论(0编辑  收藏  举报