AngularJS: traversing nested arrays

后端 未结 2 1348
我寻月下人不归
我寻月下人不归 2021-02-06 15:06

I am working with a nested array with the structure...

$scope.items = [{attr1: val1, 
  attr2: val2,
  items: [{
     attr1: val1, 
     attr2: val2,
     items:         


        
2条回答
  •  南旧
    南旧 (楼主)
    2021-02-06 15:23

    Before rendering data, you can make some preparations. One recursive run over your data to set level value and a link to the parent to each item. Example with your data using LoDash:

    var level = 0;
    _.each($scope.items, function(item){recursive(item, level)});
    
    function recursive(item, level){
        item.level = level;
        _.each(item.items, function(innerItem){
            innerItem.parent = item;
            recursive(innerItem, level+1);
        });
    }
    

    So now you can easily get parent and siblings of each item.

    find an item's parent -> item.parent

    find an item's sibling -> item.parent.items[i]

    make counts of siblings -> item.parent.items.length

    find out how many levels deep an item is nested -> item.level

    insert or delete items at any level of the nest (move operation example) ->

    newParent.items.push(item);
    _.remove(item.parent.items, function(child){return child == item;});
    

    The only minus of this approach which i met - you can not easily clone whole tree without going into endless recursion. But you can make custom cloning function which will not copy links.

提交回复
热议问题