function arrayToTree(array) {
const root = array[0]
array.shift()
const tree = {
id: root.id,
val: root.val,
children: array.length > 0 ? toTree(root.id, array) : []
}
return tree
}
function toTree(parenId, array) {
const children = []
const len = array.length
for (let i = 0; i < len; i++) {
const node = array[i]
if (node.parentId === parenId) {
children.push({
id: node.id,
val: node.val,
children: toTree(node.id, array)
})
}
}
return children
}
JavaScript数组转树
最新推荐文章于 2023-07-05 22:06:51 发布