数组转为tree结构 方法
方法一:
arrToTree(arr) {
const hash = {} // 定义一个空对象用于存储每个节点对象
const result = [] // 定义一个空数组用于存储根节点对象
for (let item of arr) {
hash[item.id] = item // 将每个节点对象存储到hash中,以id作为键
}
for (let item of arr) {
const parent = hash[item.pid] // 获取当前节点对象的父节点对象
if (parent) { // 如果存在父节点对象
if (!parent.children) { // 如果父节点对象不存在children属性,则创建一个空数组作为它的children属性
parent.children = []
}
parent.children.push(item) // 将当前节点对象添加到父节点对象的children数组中
} else { // 如果不存在父节点对象,说明当前节点对象是一个根节点对象
result.push(item) // 将当前节点对象添加到result数组中
}
}
return result // 返回根节点对象组成的result数组
}
总结:
将输入数组中的每个节点对象存储到hash中,以id作为键。遍历输入数组,对于每个节点对象,获取它的父节点对象,如果存在父节点对象,则将当前节点对象添加到父节点对象的children数组中,否则将当前节点对象添加到result数组中。最后返回根节点对象组成的result数组,就得到了一个树形结构的数组。