javascript将list转换成树状结构
2024-08-27 17:29:57
/**
* 将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));
朝朝暮暮 终于写出来了,好几年前的心愿了
最新文章
- Java总结篇系列:Java泛型
- Reactjs-JQuery-Vuejs-Extjs-Angularjs对比
- MyISAM与InnoDB区别
- Delphi String 常用字串符处理函数
- Android性能优化(一)
- 什么是Gn Gi Gb!
- mysql 慢查询开启
- ECSHOP错误Redefining already defined constructor for class如何解决
- 【.net 深呼吸】在配置节中使用元素集合
- 遍历输出tuple元素的简洁方式(C++11)
- Bootstrap方法之--排版、代码
- 结构型---组合模式(Composite Pattern)
- Markdown语法说明(转)
- 背水一战 Windows 10 (90) - 文件系统: 获取 Package 中的文件, 可移动存储中的文件操作, “库”管理
- laravel5.3 源码分析 Passport
- 使用Java对文件进行解压缩
- Fetch使用方法
- 编写自己的代码库(javascript常用实例的实现与封装)
- MHA切换过程:
- [BZOJ2286][SDOI2011]消耗战(虚树DP)
热门文章
- hostswap dcevm
- Python __slots__的使用
- 分享一篇 Git Web 开发流程
- 转-[WebServer] Windows操作系统下 Tomcat 服务器运行 PHP 的环境配置
- SPA项目中,404页面 和 登陆页面 对应的路由,应该怎样控制?
- Centos6.8 Mysql5.6 安装配置教程(转)
- Zookeeper watcher机制
- ASP.NET AJAX入门系列(8):自定义异常处理
- [转]Sublime Text 新建文件快速生成Html【头部信息】和【代码补全】、【汉化】
- 有了Jenkins,为什么还需要一个独立的部署系统