<script type="text/javascript">
var nodes=[{
id:10,
title:'文章0',
parentId:4
},
{
id:4,
title:"文章1",
parentId:2
},
{
id:2,
title:"文章2",
parentId:0,
},{
id:8,
title:"文章3",
parentId:2
},{
id:6,
title:"文章4",
parentId:4
}];
(function converToJson(){
var temp={},res={};
//将parentId相同的对象归类
for(var i in nodes){
if(!temp[nodes[i].parentId]){
temp[nodes[i].parentId] = [];
}
temp[nodes[i].parentId].push(nodes[i]);
}
res=temp[0];
var f =res;
convertD(f,temp);
console.log("---"+JSON.stringify(res[0]));
})();
//递归实现添加children节点
function convertD(f,temp){
for(var m=0;m<f.length;m++){
var t = f[m].id;
for(var i in temp){
if(t == i){
f[m].children=temp[i];
break;
}
}
if(f[m].children){
convertD(f[m].children,temp);
}
}
}
</script>
res[0]结果:
{
"id": 2,
"title": "文章2",
"parentId": 0,
"children": [{
"id": 4,
"title": "文章1",
"parentId": 2,
"children": [{
"id": 10,
"title": "文章0",
"parentId": 4
},
{
"id": 6,
"title": "文章4",
"parentId": 4
}]
},
{
"id": 8,
"title": "文章3",
"parentId": 2
}]
}