做一个无限节点的树结构插件的原理

因为公司功能扩展需要,所以我想做一个无限树结构的插件来进行更新。
但是目前遇见了这样的一个问题,假如数据如下:
    {
        name: '水果', id: 1, children: [
            {name:'水果1',id:2,children:[
                {name:'水果2',id:3,children:[
                    {name:'水果2',id:3,children:[]}        
                ]}
            ]}
        ]
    }

像这种无限扩展的子级,我每一层的每一个数据我都需要添加一个status对象。每一个层级都需要添加一个内层循环。但是我感觉这种办法太死了。请问有什么便捷的技巧或者写法呢?
于是我想到了能否用for来for,但是尝试了一下发现不行。
我又想到能否用递归实现呢?但是小弟对递归的作用还不算太明白所以没有实现。
想问下,像我这种问题有什么办法可以实现用最少的代码做到每个数据里面都能给他一个status呢?

app.directive('tree',function(){
    return {
        restrict:'E',
        replace:true,
        scope:{
            list:"=",
            resData:"=",
            layer:"@"
        },
        templateUrl:"template/tree.html",
        link:function(scope,elem,attr){
            console.log(scope.list)
            for(var i in scope.list){
                scope.list[i].status=false;
                if(scope.list.children){
                    for(var k in scope.lists[i].children){
                        scope.list[i].children[k].status=false;
                    }
                }
            }
        }
    }
})
阅读 3.6k
2 个回答
  var data = [{name: '水果', id: 1, children: [
            {name:'水果1',id:2,children:[
                {name:'水果2',id:3,children:[
                    {name:'水果2',id:3,children:[]}        
                ]}
            ]}
        ]
    }];
    
 function render(data){
         
    data.forEach(function(item,index){
        item.status = false;
        if(item.children){
            render(item.children);
        }
    }); 
    console.log(JSON.stringify(data));
    return data;
 }
 
 render(data);
function set(obj){ 
  if(!!!obj.status) obj.status = "1"; 
  if(obj.children.length > 0)
     $.each(obj.children, function(i,o){set(o)});
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题