前提是讓后端給返回一個(gè)當(dāng)前選擇的樹(shù)
例:
//已選擇的樹(shù)deptsTree你雌,
const deptsTree: any =
{
id: 1,
parentId: 0,
children: [
{
id: 94,
parentId: 1,
children: [
{
id: 95,
parentId: 94,
children: [],
sort: 1,
parentDeptId: 94,
deptName: '門(mén)-葉子',
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: '大樹(shù)的根根1',
level: 1,
status: 'ENABLE',
remark: null
},
{
id: 57,
parentId: 56,
children: [],
sort: 11,
parentDeptId: 56,
deptName: '二級(jí)部門(mén)',
level: 2,
status: 'ENABLE',
remark: '11'
},
{
id: 101,
parentId: 0,
children: [],
sort: 99,
parentDeptId: 0,
deptName: '稱(chēng)',
level: 1,
status: 'ENABLE',
remark: ''
},
{
id: 70,
parentId: 69,
children: [],
sort: 2343,
parentDeptId: 69,
deptName: '測(cè)的部',
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[] {
// 合并節(jié)點(diǎn)
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()