js 把线性的数据结构改成树形结构
来源:互联网 发布:java截取汉字字符串 编辑:程序博客网 时间:2024/05/21 05:19
把数组的数据结构改成树形结构。
var aaa = [{name:"111", id: 1, pId: 0, children: []},{name:"222", id: 6, pId: 0, children: []},{name:"b", id: 2, pId: 1, children: []},{name:"c", id: 3, pId: 1, children: []},{name:"d", id: 4, pId: 2, children: []},{name:"d", id: 4, pId: 6, children: []},]function Tree(data) {this.tree = data||[]; //数据this.groups = {}; //分组}Tree.prototype = {init: function(pid) {this.group();var data = this.getData(this.groups[pid]);return data;},group: function () { for(var i=0; i<this.tree.length; i++){ if(this.groups[this.tree[i].pId]){ this.groups[this.tree[i].pId].push(this.tree[i]); }else{ this.groups[this.tree[i].pId]=[]; this.groups[this.tree[i].pId].push(this.tree[i]); } }},getData: function (info) { if (!info) return;var children = [];for (var i = 0; i < info.length; i++) {var item = info[i];item.children = item['children'].concat(this.getData(this.groups[item.id]));children.push(item);}return children;}}var d = new Tree(aaa).init(0);console.log(JSON.stringify(d));
我的主要思路是有两步。
1 分组
将所有pId 相同的数据放入一个数组中,
2 从树形结构的最顶层开始查找(pId = 0)。来根据id 递归查找子集。
阅读全文
0 0
- js 把线性的数据结构改成树形结构
- js的 树形结构
- 树形结构转线性结构的方法
- 树形结构转线性结构的方法(帖子汇总)
- 树形结构转换线性结构的方法(lca倍增)
- 将给定格式的线性结构转换为树形结构
- 数据结构——树形结构的应用
- 数据结构中的是树形的结构
- 数据结构之树形结构
- 数据结构-树形结构实例
- 数据结构---树形结构
- 数据结构--树形结构
- 我的数据结构思考--理解线性结构
- 【数据结构】线性表的顺序存储结构
- 【数据结构】线性表的链式存储结构
- 数据结构线性表顺序结构的实现
- 数据结构中线性表的存储结构
- 【数据结构练习】基于线性结构的队列
- iOS 内省方法浅谈
- mybatis 传入null值解决方法
- 深入理解Java中的final关键字
- java设计模式汇总
- STM32时钟配置方法详解
- js 把线性的数据结构改成树形结构
- android 标题栏颜色渐变和阴影
- 如何将本地项目上传至GitHub(so easy!!!)
- redis之基本命令
- 51nod 1110 距离之和最小 V3
- Mybatis-generator 逆向工程
- Flume实战(实时导入日志内容进ODPS)
- Makefile四书写命令
- js调用原生方法解决办法