实现
- 映射id和值,利用引用类型的特性,最后所有的元素都会连接到一起
function arrToTree(arr) {
if (Object.prototype.toString.call(arr) !== '[object Array]' || arr.length <= 0) return arr
let map = {}, res
arr.forEach(el => map[el.id] = el )
arr.forEach(el => {
// 如果有父元素,让它连接到父元素,否则没有父元素,就是根节点
if (map[el.pid]) {
map[el.pid].children = map[el.pid].children || []
map[el.pid].children.push(el)
}else {
res = el
}
})
return res
}
- 层序遍历
function arrToTree(arr) {
if (Object.prototype.toString.call(arr) !== '[object Array]' || arr.length <= 0) return arr
let root
// 找到根节点
arr.forEach(el => {
if (el.pid === null) root = el
})
let queue = [root]
let _arr = arr.map(el => el)
while(queue.length > 0) {
let size = queue.length
while(size--) {
let node = queue.shift()
for (let i = _arr.length-1; i >= 0; i--) {
if (_arr[i].pid === node.id) {
queue.push(_arr[i])
node.children = node.children || []
node.children.push(_arr[i])
_arr.splice(i, 1)
}
}
}
}
return root
}
数据
var arr = [{
id: 1001,
value: 1,
pid: null,
}, {
id: 1004,
value: 4,
pid: 1002
}, {
id: 1002,
value: 2,
pid: 1001
}, {
id: 1003,
value: 3,
pid: 1001
}, {
id: 1005,
value: 5,
pid: 1003
}]
结果