js 把线性的数据结构改成树形结构
生活随笔
收集整理的這篇文章主要介紹了
js 把线性的数据结构改成树形结构
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
把數組的數據結構改成樹形結構。
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 遞歸查找子集。
總結
以上是生活随笔為你收集整理的js 把线性的数据结构改成树形结构的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (视频+图文)机器学习入门系列-第3章
- 下一篇: 腾讯视频网页下载_腾讯视频怎么下载视频