/**
* 将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));

朝朝暮暮 终于写出来了,好几年前的心愿了

最新文章

  1. Java总结篇系列:Java泛型
  2. Reactjs-JQuery-Vuejs-Extjs-Angularjs对比
  3. MyISAM与InnoDB区别
  4. Delphi String 常用字串符处理函数
  5. Android性能优化(一)
  6. 什么是Gn Gi Gb!
  7. mysql 慢查询开启
  8. ECSHOP错误Redefining already defined constructor for class如何解决
  9. 【.net 深呼吸】在配置节中使用元素集合
  10. 遍历输出tuple元素的简洁方式(C++11)
  11. Bootstrap方法之--排版、代码
  12. 结构型---组合模式(Composite Pattern)
  13. Markdown语法说明(转)
  14. 背水一战 Windows 10 (90) - 文件系统: 获取 Package 中的文件, 可移动存储中的文件操作, “库”管理
  15. laravel5.3 源码分析 Passport
  16. 使用Java对文件进行解压缩
  17. Fetch使用方法
  18. 编写自己的代码库(javascript常用实例的实现与封装)
  19. MHA切换过程:
  20. [BZOJ2286][SDOI2011]消耗战(虚树DP)

热门文章

  1. hostswap dcevm
  2. Python __slots__的使用
  3. 分享一篇 Git Web 开发流程
  4. 转-[WebServer] Windows操作系统下 Tomcat 服务器运行 PHP 的环境配置
  5. SPA项目中,404页面 和 登陆页面 对应的路由,应该怎样控制?
  6. Centos6.8 Mysql5.6 安装配置教程(转)
  7. Zookeeper watcher机制
  8. ASP.NET AJAX入门系列(8):自定义异常处理
  9. [转]Sublime Text 新建文件快速生成Html【头部信息】和【代码补全】、【汉化】
  10. 有了Jenkins,为什么还需要一个独立的部署系统