ZhouYing-JOEY / practice

手写练习整理
1 stars 0 forks source link

对象列表转树结构 #2

Open ZhouYing-JOEY opened 2 years ago

ZhouYing-JOEY commented 2 years ago

function computTreeList(list, id = "id", pid = "pid") { let treeData= list; let arr = []; treeData.forEach((item, index) => { let isParent = false; treeData.forEach(item2 => { if (item[pid] && item[pid] == item2[id]) { isParent = true; !Array.isArray(item2.children) && (item2.children = []); item2.children.push(item); } }); !isParent && arr.push(index); }); return treeData.filter((_, index) => arr.indexOf(index) > -1); }

ZhouYing-JOEY commented 2 years ago

注意是否需要改变源数据,不能改的话加个深克隆