递归列表
let list = [ { actiontype: "Add,Delete,Edit,Show", description: "", icon: "", menucode: "00", menuname: "商品管理", menupath: "", menutype: "main", parentcode: "", sortby: "1", }, { actiontype: "Add,Delete,Edit,Show", description: "", icon: "", menucode: "0001", menuname: "商品维度", menupath: "WaresManage/WaresDimension", menutype: "main", parentcode: "00", sortby: "1", }, { actiontype: "Add,Delete,Edit,Show", description: "", icon: "", menucode: "0002", menuname: "商品品类", menupath: "WaresManage/WaresCategories", menutype: "main", parentcode: "00", sortby: "2", } ] const toTree = (data) => { var map = {}; data.forEach(function (item) { map[item.menucode] = item; }); console.log(map) var val = []; data.forEach(function (item) { var parent = map[item.parentcode]; console.log(parent, item) if (parent) { (parent.children || ( parent.children = [] )).push(item); } else { //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中,作为顶级 val.push(item); } }); return val; } let menus = toTree(list); 修改后结果如下: menues: [ { "actiontype": "Add,Delete,Edit,Show", "description": "", "icon": "", "menucode": "00", "menuname": "商品管理", "menupath": "", "menutype": "main", "parentcode": "", "sortby": "1", "children": [ { "actiontype": "Add,Delete,Edit,Show", "description": "", "icon": "", "menucode": "0001", "menuname": "商品维度", "menupath": "WaresManage/WaresDimension", "menutype": "main", "parentcode": "00", "sortby": "1" }, { "actiontype": "Add,Delete,Edit,Show", "description": "", "icon": "", "menucode": "0002", "menuname": "商品品类", "menupath": "WaresManage/WaresCategories", "menutype": "main", "parentcode": "00", "sortby": "2" } ] } ]