关于父子节点无限级查询

wass4035 发布于 2015/05/19 16:35
阅读 262
收藏 0

正常情况下 数据库中查询出来的结果是这样的json   [{'id':'1' ,'name':'1',fid='0'},{'id':'2' ,'name':'2',fid='1'},{'id':'3' ,'name':'3',fid='1'},{'id':'4' ,'name':'4',fid='2'},{'id':'5' ,'name':'5',fid='3'},{'id':'6' ,'name':'6',fid='4'}]

怎么让查询出来的json呈现成树形结构的

 [{'id':'1' ,'name':'1',fid='0' ,'children':[

                                    {'id':'2' ,'name':'2',fid='1','children':[

                                                                            {'id':'4' ,'name':'4',fid='2','children': [

                                                                                                {'id':'6' ,'name':'6',fid='4'}

                                                                                                                            ]}
                                                                                     ]}
                                                 
                                         {'id':'3' ,'name':'3',fid='1','children':[

                                                                            {'id':'5' ,'name':'5',fid='3'}

                                                                                         ]}
                                              ]}   ]

 

 

加载中
0
名字不能超过十个字
名字不能超过十个字
var data = [
 {'id':'1' ,'name':'1',fid:'0'},
 {'id':'2' ,'name':'2',fid:'1'},
 {'id':'3' ,'name':'3',fid:'1'},
 {'id':'4' ,'name':'4',fid:'2'},
 {'id':'5' ,'name':'5',fid:'3'},
 {'id':'6' ,'name':'6',fid:'4'}
];






function tree(data) {
 var indexs = [];
 for(var i = 0;i < data.length;i++) {
 indexs[data[i].id] = i;
 data[i].child = [];
 }
 console.log(indexs);
 for(var j = data.length-1;j >= 0;j--) {
        var _pid = data[j].fid;
        console.log("j:"+j+",pid:"+_pid);
        if(_pid !=0) {
            data[indexs[_pid]].child.push(data[j]);
            delete data[j];
            console.log("delete:"+j);
        }
 }
  
 return data;
};


console.log(tree(data));

不负责任回帖



wass4035
wass4035
如果 只是存储到一个数据缓冲对象里 也可以这样遍历吗
0
wass4035
wass4035
那如果是

var store = new Data.TreeStore({        
      url : 'admin/department/listTree',           
   map : {           
    isleaf : 'leaf',           
    name : 'text'         
    },

      autoLoad : true       
     });

这样获取的数据 只是存储到store里面  看不到数据的啊 也可以遍历么 这个前端框架是BUI框架

返回顶部
顶部