這篇文章主要為大家詳細介紹了如何在javascript中將list轉(zhuǎn)換成樹狀結(jié)構(gòu),文中示例代碼介紹的非常詳細,具有一定的參考價值,發(fā)現(xiàn)的小伙伴們可以參考一下:
成都創(chuàng)新互聯(lián)公司主營荔浦網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,app軟件開發(fā)公司,荔浦h5微信小程序開發(fā)搭建,荔浦網(wǎng)站營銷推廣歡迎荔浦等地區(qū)企業(yè)咨詢
1.JavaScript主要用來向HTML頁面添加交互行為。 2.JavaScript可以直接嵌入到HTML頁面,但寫成單獨的js文件有利于結(jié)構(gòu)和行為的分離。 3.JavaScript具有跨平臺特性,在絕大多數(shù)瀏覽器的支持下,可以在多種平臺下運行。
如下所示:
/** * 將list裝換成tree * @param {Object} myId 數(shù)據(jù)主鍵id * @param {Object} pId 數(shù)據(jù)關(guān)聯(lián)的父級id * @param {Object} list list集合 */ function listToTree(myId,pId,list){ function exists(list, parentId){ for(var i=0; i<list.length; i++){ if (list[i][myId] == parentId) return true; } return false; } var nodes = []; // get the top level nodes for(var i=0; i<list.length; i++){ var row = list[i]; if (!exists(list, row[pId])){ nodes.push(row); } } var toDo = []; for(var i=0; i<nodes.length; i++){ toDo.push(nodes[i]); } while(toDo.length){ var node = toDo.shift(); // the parent node // get the children nodes for(var i=0; i<list.length; i++){ var row = list[i]; if (row[pId] == node[myId]){ //var child = {id:row.id,text:row.name}; if (node.children){ node.children.push(row); } else { node.children = [row]; } toDo.push(row); } } } return nodes; } var list=[ {"ids":1,"parendId":0,"name":"Foods",url:"wwww"}, {"ids":2,"parentId":1,"name":"Fruits"}, {"ids":3,"parentId":1,"name":"Vegetables"}, {"ids":4,"parentId":2,"name":"apple"}, {"ids":5,"parentId":2,"name":"orange"}, {"ids":6,"parentId":3,"name":"tomato"}, {"ids":7,"parentId":3,"name":"carrot"}, {"ids":8,"parentId":3,"name":"cabbage"}, {"ids":9,"parentId":3,"name":"potato"}, {"ids":10,"parentId":3,"name":"lettuce"}, {"ids":11,"parendId":0,"name":"Foods"}, {"ids":12,"parentId":11,"name":"Fruits"}, {"ids":13,"parentId":11,"name":"Vegetables"}, {"ids":14,"parentId":12,"name":"apple"}, {"ids":15,"parentId":12,"name":"orange"}, {"ids":16,"parentId":13,"name":"tomato"}, {"ids":17,"parentId":13,"name":"carrot"}, {"ids":18,"parentId":13,"name":"cabbage"}, {"ids":19,"parentId":13,"name":"potato"}, {"ids":20,"parentId":13,"name":"lettuce"} ]; console.log(JSON.stringify(listToTree("ids","parentId",list))); console.log(listToTree("ids","parentId",list));
以上就是創(chuàng)新互聯(lián)小編為大家收集整理的如何在javascript中將list轉(zhuǎn)換成樹狀結(jié)構(gòu),如何覺得創(chuàng)新互聯(lián)網(wǎng)站的內(nèi)容還不錯,歡迎將創(chuàng)新互聯(lián)網(wǎng)站推薦給身邊好友。
分享標題:如何在javascript中將list轉(zhuǎn)換成樹狀結(jié)構(gòu)
轉(zhuǎn)載來于:http://aaarwkj.com/article38/igjdpp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供云服務(wù)器、營銷型網(wǎng)站建設(shè)、響應(yīng)式網(wǎng)站、企業(yè)網(wǎng)站制作、全網(wǎng)營銷推廣、動態(tài)網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)