const target = [
{
id: 1,
name: '流程管理',
children: [
{ id: 2, name: '请假流程' },
{ id: 3, name: '报销流程' },
{
id: 4,
name: '借款流程',
children: [{ id: 5, name: '备用金流程' }],
},
],
},
{
id: 6,
name: '系统管理',
children: [
{ id: 7, name: '用户管理' },
{ id: 8, name: '角色管理' },
],
},
]
const data = [
{ id: 1, name: '流程管理', parent_id: 0 },
{ id: 2, name: '请假流程', parent_id: 1 },
{ id: 3, name: '报销流程', parent_id: 1 },
{ id: 4, name: '借款流程', parent_id: 1 },
{ id: 5, name: '备用金流程', parent_id: 4 },
{ id: 6, name: '系统管理', parent_id: 0 },
{ id: 7, name: '用户管理', parent_id: 6 },
{ id: 8, name: '角色管理', parent_id: 6 },
]
const arrayToTree = (arr, pid) => {
return arr.reduce((res, current) => {
if (current['parent_id'] === pid) {
current.children = arrayToTree(arr, current['id'])
return res.concat(current)
}
return res
}, [])
}
const treeToArray = arr => {
const res = []
arr.forEach(element => {
const { children, ...rest } = element
res.push({ ...rest })
if (element?.children?.length > 0) {
res.push(...treeToArray(children))
}
})
return res
}
const formatData = (data, pid) => {
const root = data.filter(item => {
return item['parent_id'] === pid
})
return root.map(pItem => {
return { ...pItem, children: [...formatData(data, pItem['id'])] }
})
}
const getTreeList = (data, pid, res) => {
for (const list of data) {
if (list['parent_id'] === pid) {
res.push(list)
}
for (const root of res) {
root.children = []
getTreeList(data, root.id, root.children)
if (root.children.length === 0) {
delete root.children
}
}
}
return res
}
const filterTreeList = data => {
const res = []
data.forEach(item => {
item.children = data.filter(i => {
return i['parent_id'] === item.id
})
if (item.children.length === 0) {
delete item.children
}
if (item['parent_id'] === 0) {
res.push(item)
}
res.push(item)
})
return res
}
console.log(filterTreeList(data))