递归实现N级目录
// data var menuList = [ { Name: '1级1', id: '1' }, { Name: '1级2', id: '2', }, { Name: '1级1-1', id: '3', parent: '1' }, { Name: '1级2-1', id: '4', parent: '2' }, { Name: '好多级', id: '5', parent: '3', }, { Name: '好多级2', id: '6', parent: '5', } ];
function sonMenu(obj, arr) { var child = [] for (var i = 0; i < arr.length; i++) { if (arr[i].parent === obj.id) { sonMenu(arr[i], arr); child.push(arr[i]); } } if (child.length > 0) { obj.children = child; } return obj; } function menuInit(data) { let ptree = []; for (var i = 0; i < data.length; i++) { if (!data[i].parent) {//获取父元素 let o = sonMenu(data[i], data); ptree.push(o); } } return ptree; }