javascript將list轉換成樹狀結構的實例
更新時間:2017年09月08日 09:08:37 作者:思思博士
下面小編就為大家?guī)硪黄猨avascript將list轉換成樹狀結構的實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
如下所示:
/** * 將list裝換成tree * @param {Object} myId 數(shù)據(jù)主鍵id * @param {Object} pId 數(shù)據(jù)關聯(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));
以上這篇javascript將list轉換成樹狀結構的實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
原生js實現(xiàn)查找/添加/刪除/指定元素的class
查找、添加、刪除、指定元素的class使用原生js實現(xiàn)不可思議吧,感興趣的朋友可以參考下哈,希望可以幫助到你2013-04-04uniapp微信小程序訂閱消息發(fā)送服務通知超詳細教程
在使用或開發(fā)小程序過程中,我們會發(fā)現(xiàn)消息通知是非常重要的一個環(huán)節(jié),下面這篇文章主要給大家介紹了關于uniapp微信小程序訂閱消息發(fā)送服務通知的相關資料,需要的朋友可以參考下2023-06-06JavaScript實現(xiàn)重置表單(reset)的方法
這篇文章主要介紹了JavaScript實現(xiàn)重置表單(reset)的方法,涉及javascript中reset()方法的使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-04-04記錄微信小程序 height: calc(xx - xx);無效問題
這篇文章主要介紹了微信小程序 - height: calc(xx - xx);無效 問題,文中給大家擴展介紹下jquery點擊添加樣式,再次點擊移除樣式的實例代碼,需要的朋友可以參考下2019-12-12