let items = [
{ id: 1, pid: 0, name: '数据1' },
{ id: 2, pid: 1, name: '数据2' },
{ id: 3, pid: 1, name: '数据3' },
{ id: 4, pid: 3, name: '数据4' },
{ id: 5, pid: 4, name: '数据5' },
{ id: 6, pid: 0, name: '数据6' },
]
console.log(itemsToTreeOne(items))
function itemsToTreeOne (items) {
let obj = { }
let len = items.length
let resultTree = [ ]
for(i = 0; i < len; i++) {
if (obj['id' + items[i].id] === undefined) {
obj['id' + items[i].id] = items[i]
} else {
Object.assign(obj['id' + items[i].id], items[i])
}
if (items[i].pid === 0) {
resultTree.push(obj['id' + items[i].id])
} else {
if (obj['id' + items[i].pid] === undefined) {
obj['id' + items[i].pid] = { children: [ ] }
}
if (obj['id' + items[i].pid].children === undefined) {
obj['id' + items[i].pid].children = [ ]
}
obj['id' + items[i].pid].children.push(items[i])
}
}
return resultTree
}
function itemsToTreeTwo (items) {
let obj = { }
let len = items.length
for(i = 0; i < len; i++) {
obj['id' + items[i].id] = items[i]
obj['id' + items[i].id].children = [ ]
}
let resultTree = [ ]
for(i = 0; i < len; i++) {
if (items[i].pid === 0) {
resultTree.push(obj['id' + items[i].id])
} else {
obj['id' + items[i].pid].children.push(items[i])
}
}
return resultTree
}
|