// array:源数据,parentId:父级id字段,id:id字段
arrayToTree(array,parentId,id) {
const map = new Map()
const result = []
for (const item of array) {
map.set(item[id], { ...item, children: [] })
}
for (const [key, item] of map) {
if (item[parentId] == 0 || item[parentId] == null) {
result.push(item)
} else {
const parent = map.get(item[parentId])
if (parent) {
parent.children.push(item)
}
}
}
result.forEach(node => this.deleteEmptyChildren(node))
return result
},
deleteEmptyChildren(node) {
if (node.children && node.children.length === 0) {
delete node.children
} else {
node.children.forEach(child => this.deleteEmptyChildren(child))
}
}