1. Directly upload the code
export function getTreeListData(list, parentId, uniqueId) {
let dataArray = [];
list.forEach(function(data) {
let departmentParentId = data[parentId];
if (departmentParentId === "0") {
dataArray.push(data);
}
});
return data2treeDG(list, dataArray, parentId, uniqueId);
}
function data2treeDG(datas, dataArray, parentId, uniqueId) {
for (let j = 0; j < dataArray.length; j++) {
let dataArrayIndex = dataArray[j];
let childrenArray = [];
let Id = dataArrayIndex[uniqueId];
for (let i = 0; i < datas.length; i++) {
let data = datas[i];
let departmentParentId = data[parentId];
if (departmentParentId == Id) {
childrenArray.push(data);
}
}
if (childrenArray.length > 0) {
dataArrayIndex.children = childrenArray;
data2treeDG(datas, childrenArray, parentId, uniqueId);
}
}
return dataArray;
}
2. Best performance
function arrayToTree2(items, fid=0) {
const result = [];
const itemMap = {
};
for (const item of items) {
const id = item.id;
const pid = item.pid;
if (!itemMap[id]) {
itemMap[id] = {
children: [],
}
}
itemMap[id] = {
...item,
children: itemMap[id]['children']
}
const treeItem = itemMap[id];
if (pid === fid) {
result.push(treeItem);
} else {
if (!itemMap[pid]) {
itemMap[pid] = {
children: [],
}
}
itemMap[pid].children.push(treeItem)
}
}
return result;
}