toTree (arr) {
let tree = []
const map = {}
for (let item of arr) {
// 一个新的带children的结构
let newItem = map[item.id] = {
id:item.id,
parentId:item.parentId,
title:item.title,
value:item.id,
key:item.id,
children: []
}
if (map[item.parentId]) { // 父节点已存进map则在父节点的children添加新元素
let parent = map[item.parentId]
parent.children.push(newItem)
} else { // 没有父节点,在根节点添加父节点
tree.push(newItem)
}
}
return tree
},
数组转树结构
最新推荐文章于 2024-07-19 13:54:51 发布