1 回答
TA贡献2003条经验 获得超2个赞
递归构建tree即可:
var list = [{ Id: 10, parentId: -1, level: 1 }, { Id: 101, parentId: 10, level: 2 }, { Id: 102, parentId: 10, level: 2 }, { Id: 103, parentId: 10, level: 2 }, { Id: 111, parentId: 101, level: 3 }, { Id: 112, parentId: 101, level: 3 }, { Id: 121, parentId: 102, level: 3 }, { Id: 1001, parentId: 121, level: 4 }]
var arr = [];
function sortToGetTree(list, pid) {
if (list != null) {
for (var i = 0; i < list.length; i++) {
if (list[i].parentId == pid) {
arr.push(list[i]);
sortToGetTree(list, list[i].Id);
}
}
}
return ;
}
sortToGetTree(list,list[0].Id);
console.log(arr);
结果:
添加回答
举报