javascript将list转换成树状结构的实例
程序员文章站
2022-09-08 13:04:25
如下所示:
/**
* 将list装换成tree
* @param {object} myid 数据主键id
* @param {obje...
如下所示:
/** * 将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转换成树状结构的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。