/**
* @derection 获取树形结构数据
* @params [array] list 包含父子关系的数组 id parentid
* @return 返回树形结构数据数组
*/
export function GetTreeStructure(list){
const idMapping = list.reduce((acc, el, i) => {
acc[el.id] = i;
return acc;
}, {});
let root=new Array();
list.forEach(el => {
// 判断根节点
if (idMapping[el.parentId] === undefined) {
root.push(el);
return;
}
// 用映射表找到父元素
const parentEl = list[idMapping[el.parentId]];
// 把当前元素添加到父元素的`children`数组中
parentEl.list = [...(parentEl.list || []), el];
});
return root
}
js递归树
于 2022-11-01 17:19:58 首次发布