前提是让后端给返回一个当前选择的树
例:
//已选择的树deptsTree,
const deptsTree: any =
{
id: 1,
parentId: 0,
children: [
{
id: 94,
parentId: 1,
children: [
{
id: 95,
parentId: 94,
children: [],
sort: 1,
parentDeptId: 94,
deptName: '门-叶子',
level: 3,
status: 'DISABLE',
remark: 'ee'
}
]
}
]
}
//获取到的列表
const depList: any= [
{
id: 1,
parentId: 0,
children: [
{
id: 46,
parentId: 1,
children: [
{
id: 47,
parentId: 46,
children: [],
sort: 3,
parentDeptId: 46,
deptName: '板烧鸡腿堡',
level: 3,
status: 'ENABLE',
remark: null
}
],
sort: 2,
parentDeptId: 1,
deptName: '汉堡包',
level: 2,
status: 'ENABLE',
remark: null
},
{
id: 48,
parentId: 1,
children: [],
sort: 2,
parentDeptId: 1,
deptName: '披萨',
level: 2,
status: 'ENABLE',
remark: null
}
],
sort: 1,
parentDeptId: 0,
deptName: '大树的根根1',
level: 1,
status: 'ENABLE',
remark: null
},
{
id: 57,
parentId: 56,
children: [],
sort: 11,
parentDeptId: 56,
deptName: '二级部门',
level: 2,
status: 'ENABLE',
remark: '11'
},
{
id: 101,
parentId: 0,
children: [],
sort: 99,
parentDeptId: 0,
deptName: '称',
level: 1,
status: 'ENABLE',
remark: ''
},
{
id: 70,
parentId: 69,
children: [],
sort: 2343,
parentDeptId: 69,
deptName: '测的部',
level: 3,
status: 'ENABLE',
remark: ''
}
]
interface TreeNode {
id: number
parentId: number
children: TreeNode[]
sort?: number
parentDeptId?: number
deptName?: string
level?: number
status?: string
remark?: string
}
//合并方法
export function mergeTrees(deptsTree: TreeNode[], mm: TreeNode): TreeNode[] {
// 合并节点
function mergeNodes(nodes: TreeNode[], item: TreeNode) {
for (const node of nodes) {
const outIds = nodes.map((el: any) => el.id)
if (outIds.indexOf(item.id) == -1) {
nodes.push(item)
return
}
if (node.id == item.id) {
const childrenIds = node.children.map((el: any) => el.id)
if (item.children.length > 0 && childrenIds.indexOf(item.children[0].id) == -1) {
const childItem: any = item.children[0]
node.children.push(childItem)
return
} else {
if (node.children && node.children.length > 0 && item.children && item.children.length > 0) {
mergeNodes(node.children, item.children[0])
break
}
}
}
}
}
mergeNodes(deptsTree, mm)
return deptsTree
}
let newTree = mergeTrees(res1, deptTree)
console.log()