行資料結構轉成樹形資料結構
阿新 • • 發佈:2018-12-01
背景:在前後端開發過程中,後端負責提供介面資料,有時前端需要把介面資料轉成其他的格式,本文就用於將具備父子邏輯的行資料轉成樹形結構。
程式碼如下:
function rowDataToTreeData(rootTreeNode, rowData) { if (rowData && rowData.length > 0) { for (let i = 0; i < rowData.length; i++) { //找出子節點 if (rootTreeNode.id === rowData[i].parentId) { if (rootTreeNode.children) { rootTreeNode.children.push(rowData.splice(i, 1)[0]); } else { rootTreeNode.children = [rowData.splice(i, 1)[0]]; } i = i - 1; } } if (rootTreeNode.children && rootTreeNode.children.length > 0) { for (let i = 0; i < rootTreeNode.children.length; i++) { this.rowDataToTreeData(rootTreeNode.children[i], rowData);//遞迴 } } } return rootTreeNode; } let rootTreeNode = {//假設的根節點,便於遞迴邏輯 id: 0, parentId: undefined, children: [] }; let rowData = [ { id: 1, parentId: 0, name: 1 }, { id: 2, parentId: 0, name: 2 }, { id: 3, parentId: 1, name: 3 }, { id: 4, parentId: 2, name: 49 }, { id: 5, parentId: 3, name: 5 }, { id: 6, parentId: 0, name: 6 }, { id: 7, parentId: 6, name: 7 }, { id: 8, parentId: 0, name: 8 }, { id: 9, parentId: 4, name: 9 }, { id: 10, parentId: 7, name: 10 }, { id: 11, parentId: 10, name: 11 }, { id: 12, parentId: 10, name: 12 } ]; console.log(rowDataToTreeData(rootTreeNode,rowData));
備註:資料量很大的情況並沒有測試,效能不能保證,如有道友參考需謹慎…