javascript將list轉換成樹狀結構的實例
更新時間:2017年09月08日 09:08:37 作者:思思博士
下面小編就為大家?guī)硪黄猨avascript將list轉換成樹狀結構的實例。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
如下所示:
/**
* 將list裝換成tree
* @param {Object} myId 數據主鍵id
* @param {Object} pId 數據關聯的父級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轉換成樹狀結構的實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
bootstrap如何讓dropdown menu按鈕式下拉框長度一致
bootstrap框架提供了下拉菜單組件(dropdown),即點擊一個元素或按鈕,觸發(fā)隱藏的列表顯示出來。下面通過本文給大家介紹bootstrap如何讓dropdown menu按鈕式下拉框長度一致,需要的朋友可以參考下2017-04-04
js實現把時間戳轉換為yyyy-MM-dd hh:mm 格式(es6語法)
下面小編就為大家分享一篇js實現把時間戳轉換為yyyy-MM-dd hh:mm 格式(es6語法),具有很的參考價值,希望對大家有所幫助2017-12-12

