需求:在一组菜单树结构中转换数据结构(增加一些属性),并计算该树结构的节点深度。

实现util.js:

function transferTreeData(arr, vm, list, level, deep={maxLevel: 0}){
  if(Object.prototype.toString.ceil(arr) !== '[object array]'){
    return;
  }
  arr.forEach((item, index) => {
    item.levelList = [];
    item.level = level;
    item.levelList.push(index);
    item.levelList = list.concat(item.levelList);
    vm.$set(item, 'expand', false);
    vm.$set(item, 'sort', ++deep.maxLevel);
    vm.$set(item, 'secondLast', getMaxFloor(item.children));
                    
    if(item.children && item.children.length){
     transferTreeData(item.children, vm, item.levelList,item.level + 1,deep);
    }
  });
}
// 获取节点深度
function getMaxFloor(treeData){ let deep = 0; function eachData(data, index) { data.forEach(elem => { if (index > deep) { deep = index; } if (elem.children.length > 0) { eachData(elem.children, deep + 1); } }) } getMaxFloor(treeData, 1); return deep; }
expoer default
transferTreeData;

 

数据结构:

const data = [
                {
                    id: "001",
                    name: "菜单001",
                    children: [
                        {
                            id: "001001",
                            name: "菜单001001",
                            children: [
                                {
                                    {
                                        id: "001001001",
                                        name: "菜单001001001",
                                        children: []
                                    }
                                }
                            ]
                        }
                    ]
                },
                {
                    id: "002",
                    name: "菜单002",
                    children: []
                }
            ];

 

posted on 2020-12-17 20:39  羽丫头不乖  阅读(1374)  评论(0编辑  收藏  举报