美文网首页
使用递归实现树状菜单

使用递归实现树状菜单

作者: 取个帅气的名字真好 | 来源:发表于2018-07-27 14:53 被阅读54次
var data = [  
   {menuId: 1, parentId: 0, name: "系统管理"},
  {menuId: 2, parentId: 0, name: "测试"},
  {menuId: 2, parentId: 1, name: "管理员管理"},
  {menuId: 3, parentId: 1, name: "权限管理"},
  {menuId: 4, parentId: 1, name: "菜单管理"},
  {menuId: 15, parentId: 2, name: "查看"},
  {menuId: 16, parentId: 2, name: "新增"},
  {menuId: 17, parentId: 2, name: "修改"},
  {menuId: 18, parentId: 2, name: "删除"},
  {menuId: 19, parentId: 3, name: "查看"}
];

function sonsTree(obj, arr) {
    var children = new Array();
    for (var i = 0; i < arr.length; i++) {
        if (arr[i].parentId == obj.menuId) {  //等于加入数组
            sonsTree(arr[i], arr);//递归出子元素
            children.push(arr[i]);
        }
    }
    if (children.length > 0) {
        obj.children = children;
    }
    return obj;
}

function treeUtils(data) {
    let ptree = [];
    for (var i = 0; i < data.length; i++) {
        if (data[i].parentId == 0) {//获取父元素
            let o = sonsTree(data[i], data);
            ptree.push(o);
        }
    }

    console.log(ptree);
    console.log(JSON.stringify(ptree, null, 1))
    return ptree;
}

treeUtils(data)

对应element的Tree 树形控件

数据效果:

[
 {
  "menuId": 1,
  "parentId": 0,
  "name": "系统管理",
  "children": [
   {
    "menuId": 2,
    "parentId": 1,
    "name": "管理员管理",
    "children": [
     {
      "menuId": 15,
      "parentId": 2,
      "name": "查看"
     },
     {
      "menuId": 16,
      "parentId": 2,
      "name": "新增"
     },
     {
      "menuId": 17,
      "parentId": 2,
      "name": "修改"
     },
     {
      "menuId": 18,
      "parentId": 2,
      "name": "删除"
     }
    ]
   },
   {
    "menuId": 3,
    "parentId": 1,
    "name": "权限管理",
    "children": [
     {
      "menuId": 19,
      "parentId": 3,
      "name": "查看"
     }
    ]
   },
   {
    "menuId": 4,
    "parentId": 1,
    "name": "菜单管理"
   }
  ]
 },
 {
  "menuId": 2,
  "parentId": 0,
  "name": "测试",
  "children": [
   {
    "menuId": 15,
    "parentId": 2,
    "name": "查看"
   },
   {
    "menuId": 16,
    "parentId": 2,
    "name": "新增"
   },
   {
    "menuId": 17,
    "parentId": 2,
    "name": "修改"
   },
   {
    "menuId": 18,
    "parentId": 2,
    "name": "删除"
   }
  ]
 }
]

相关文章

网友评论

      本文标题:使用递归实现树状菜单

      本文链接:https://www.haomeiwen.com/subject/yfqgmftx.html