var data = [ {id:100000, name :"1", pid :0}, {id:100100, name :"1-1", pid :100000, }, {id:100101, name :"1-1-1", pid :100100, }, {id:200000, name :"2", pid :0, }, {id:210000, name :"2-1", pid :200000, }, {id:211000, name :"2-1-1", pid :210000, }, {id:211100, name :"2-1-1-1", pid :211000, }, {id:211110, name :"2-1-1-1-1", pid :211100, }, {id:211111, name :"2-1-1-1-1-1", pid :211110, } ] function toTree(data) { // 删除 所有 children,以防止多次调用 data.forEach(function (item) { delete item.children; }); console.log(data) // 将数据存储为 以 id 为 KEY 的 map 索引数据列 var map = {}; data.forEach(function (item) { map[item.id] = item; }); console.log(map); var val = []; data.forEach(function (item) { // 以当前遍历项,的pid,去map对象中找到索引的id var parent = map[item.pid]; console.log(parent); debugger // 好绕啊,如果找到索引,那么说明此项不在顶级当中,那么需要把此项添加到,他对应的父级中 if (parent) { (parent.children || ( parent.children = [] )).push(item); console.log(data,val); } else { //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中,作为顶级 val.push(item); } }); return val; } console.log(toTree(data))