const arr = [
{ id: 1, parent_id: null },
{ id: 2, parent_id: 1 },
{ id: 3, parent_id: 1 },
{ id: 4, parent_id: 2 },
{ id: 5, parent_id: 4 },
]
const data = arr2Tree(arr)
console.log(data)
// function arr2Tree(arr) {
// let res = []
// let obj ={}
// arr.forEach(item => obj[item.id] = item)
// arr.forEach(item => {
// const parent = obj[item['parent_id']]
// if (parent) {
// (parent.children || (parent.children = [])).push(item)
// } else {
// res.push(item)
// }
// })
// return res
// }
//function arr2Tree(arr, id = null, parentName = 'parent_id') {
// return arr.filter(item => item[parentName] === id).map(item => ({...item,children: arr2Tree(arr,item.id)}))
//}
function arr2Tree(items) {
const result = []; // 存放结果集
const itemMap = {}; //
// 先转成map存储
for (const item of items) {
itemMap[item.id] = {...item, children: []}
}
for (const item of items) {
const id = item.id;
const pid = item.pid;
const treeItem = itemMap[id];
if (pid === 0) {
result.push(treeItem);
} else {
if (!itemMap[pid]) {
itemMap[pid] = {
children: [],
}
}
itemMap[pid].children.push(treeItem)
}
}
return result;
}