美文网首页
树状结构转一维数组

树状结构转一维数组

作者: AcessCors | 来源:发表于2019-07-08 10:43 被阅读0次

    树状结构转数组方法

    // key代表子节点的对象名
    function treeTransArray(tree, key) {
          return tree.reduce(function (con, item) {
            var callee = arguments.callee;
            con.push(item);
            if (item[key] && item[key].length > 0){
              item[key].reduce(callee, con);
            }
            return con;
          }, []).map(function (item) {
            item[key] = [];
            return item;
          })
        }
    

    声明树状对象

    let obj = [{
          id:'1',
          name:'顶级父组件',
          parentKey:'0',
          children:[{
            id:'1-1',            
            name:'第1层第1个子组件',
            parentKey:'1',
            children:[{
              id:'1-1-1',
              name:'第2层第1个子组件',
              parentKey:'1-1',
              children:[],            
            },{
              id:'1-1-2',
              name:'第1层第2个子组件',
              parentKey:'1-1',
              children:[],
            },{
              id:'1-1-3',
              name:'第1层第3个子组件',
              parentKey:'1-1',
              children:[],
            }]
          },{
            id:'1-2',
            name:'第1层第2个子组件',
            parentKey:'1-1',
            children:[],
          }],
        }];
    
        var arr = treeTransArray(obj,'children'); //输出转换后数组
        console.log(arr)
    

    相关文章

      网友评论

          本文标题:树状结构转一维数组

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