-
郎朗坤
您不需要递归,只需要一个对象来保持对节点和父节点的引用。这种方法也适用于未排序的数据,因为它同时使用了从项到父项和从父项到项的关系。const source = [{ id: 1, title: 'title1', alias: 'alias1', parent_id: null }, { id: 2, title: 'title2', alias: 'alias2', parent_id: null }, { id: 3, title: 'title3', alias: 'alias3', parent_id: 2 }, { id: 4, title: 'title4', alias: 'alias4', parent_id: 2 }, { id: 5, title: 'title5', alias: 'alias5', parent_id: 4 }, { id: 6, title: 'title6', alias: 'alias6', parent_id: 4 }], tree = function (data, root) { var t = {}; data.forEach(({ parent_id, ...o }) => { Object.assign(t[o.id] = t[o.id] || {}, o); t[parent_id] = t[parent_id] || {}; t[parent_id].items = t[parent_id].items || []; t[parent_id].items.push(t[o.id]); }); return t[root].items; }(source, null);console.log(tree);.as-console-wrapper { max-height: 100% !important; top: 0; }
-
长风秋雁
首先我正在尝试一棵树,但在看到@nina-scholz答案之后。我决定以同样的方式编写代码ES6。const source = [ { id: 1, title: "title1", alias: "alias1", parent_id: null }, { id: 2, title: "title2", alias: "alias2", parent_id: null }, { id: 3, title: "title3", alias: "alias3", parent_id: 2 }, { id: 4, title: "title4", alias: "alias4", parent_id: 2 }, { id: 5, title: "title5", alias: "alias5", parent_id: 4 }, { id: 6, title: "title6", alias: "alias6", parent_id: 4 }];const [result] = source.reduce( ([r, map], item) => { const d = { ...item, children: [] }; const loc = map[item.parent_id]; if (loc) { loc.children.push(d); } else { r.push(d); } map[item.id] = d; return [r, map]; }, [[], {}]);console.log(JSON.stringify(result, null, 4));.as-console-row {color: blue!important}
-
陪伴而非守候
遍历结果数组的每个对象。如果对象 id 与当前对象的父 id 不匹配,则执行递归调用以检查其项目。 function findParentAndPushChild(object,resArray){ resArray.forEach( (child)=> { if(child.id == object.parent_id)child.items.push(object); else if(child.items.length!=0)findParentAndPushChild(object,child.items); }); }检查以下代码片段。const source = [{ id: 1,title:'title1',alias:'alias1',parent_id: null},{id: 2,title:'title2',alias: 'alias2',parent_id: null},{id: 3,title:'title3',alias:'alias3',parent_id: 2},{ id: 4,title:'title4',alias:'alias4',parent_id: 2},{id: 5,title:'title5',alias:'alias5',parent_id: 4},{id: 6,title:'title6',alias:'alias6',parent_id: 4} ];let resultArray=[];source.map( obj =>{obj.items=[];return obj}).forEach(obj=>{ if(obj.parent_id==null)resultArray.push(obj); else{ let index=resultArray.findIndex( (resObj)=>resObj.id==obj.parent_id); if( index == -1)findParentAndPushChild(obj,resultArray) else resultArray[index].items.push(obj); }}) function findParentAndPushChild(object,resArray){ resArray.forEach( (child)=> {if(child.id == object.parent_id)child.items.push(object); else if(child.items.length!=0)findParentAndPushChild(object,child.items); }); } console.log(resultArray);.as-console-wrapper { max-height: 100% !important; top: 0; }