常情况下 数据库中查询出来的结果是这样的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'}
]}
]} ]
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));
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。