<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <script type="text/javascript"> function translateDataToTree(data) { let parents = data.filter(value => value.parentId == 'undefined' || value.parentId == null) let children = data.filter(value => value.parentId !== 'undefined' && value.parentId != null) let translator = (parents, children) => { parents.forEach((parent) => { children.forEach((current, index) => { if (current.parentId === parent.id) { let temp = JSON.parse(JSON.stringify(children)) temp.splice(index, 1) translator([current], temp) typeof parent.children !== 'undefined' ? parent.children.push(current) : parent.children = [current] } } ) } ) } translator(parents, children) return parents } /** * 該方法用於將有父子關系的數組轉換成樹形結構的數組 * 接收一個具有父子關系的數組作為參數 * 返回一個樹形結構的數組 */ function translateDataToTree(data) { //沒有父節點的數據 let parents = data.filter(value => value.parentId == 'undefined' || value.parentId == null) //有父節點的數據 let children = data.filter(value => value.parentId !== 'undefined' && value.parentId != null) //定義轉換方法的具體實現 let translator = (parents, children) => { //遍歷父節點數據 parents.forEach((parent) => { //遍歷子節點數據 children.forEach((current, index) => { //此時找到父節點對應的一個子節點 if (current.parentId === parent.id) { //對子節點數據進行深復制,這里只支持部分類型的數據深復制,對深復制不了解的童靴可以先去了解下深復制 let temp = JSON.parse(JSON.stringify(children)) //讓當前子節點從temp中移除,temp作為新的子節點數據,這里是為了讓遞歸時,子節點的遍歷次數更少,如果父子關系的層級越多,越有利 temp.splice(index, 1) //讓當前子節點作為唯一的父節點,去遞歸查找其對應的子節點 translator([current], temp) //把找到子節點放入父節點的children屬性中 typeof parent.children !== 'undefined' ? parent.children.push(current) : parent.children = [current] } } ) } ) } //調用轉換方法 translator(parents, children) //返回最終的結果 return parents } </script> </body> </html>
---------------------------------------------------------------
/*轉化函數*/ function(data, attributes) { let resData = data; let tree = []; for(let i = 0; i < resData.length; i++) { if(resData[i][attributes.parentId] === attributes.rootId) { let obj = { id: resData[i][attributes.id], title: resData[i][attributes.name], children: [] }; tree.push(obj); resData.splice(i, 1); i--; } } run(tree); function run(chiArr) { if(resData.length !== 0) { for(let i = 0; i < chiArr.length; i++) { for(let j = 0; j < resData.length; j++) { if(chiArr[i].id == resData[j][attributes.parentId]) { let obj = { id: resData[j][attributes.id], title: resData[j][attributes.name], children: [] }; chiArr[i].children.push(obj); resData.splice(j, 1); j--; } } run(chiArr[i].children); } } } return tree; } 1 var data=[{id:1,parentId:0,name:"測試1"}, 1 {id:2,parentId:1,name:"測試2"}] 1 2 3 4 5 <em id="__mceDel"><br>let attributes = { //定義數據屬性名稱 id: 'id', parentId: 'parentId', name: 'groupName',<br>rootId: 0 }<br>/*調用*/<br>formatTreeData(data,attributes);<br></em>