前端将列表数据转树型数据
场景:后端返回列表数据,由前端根据业务需求完成树型数据转换,
常用于侧边导航菜单,下拉树型数据项等
js
export function listToTree(data: []) {
var map: any = {},
tree: any = []
data.forEach((item: any) => {
delete item?.children
delete item?.params
if (!item.label) {
item.label = item?.name ?? item?.title
}
if (!item.value) {
item.value = item?.id
}
map[item?.id] = item
})
/**
* 以原数据量循环拼装父,子级
*/
data.forEach((item: any) => {
var parent = map[item?.pid]
if (parent) {
(parent.children || (parent.children = [])).push(item)
} else {
tree.push(item)
}
})
return tree
}
如:菜单