美文网首页
如何统计tree每一级的个数?

如何统计tree每一级的个数?

作者: 姜治宇 | 来源:发表于2023-03-07 14:46 被阅读0次

    统计总数

    对于带有children的结构性数据,如果是统计总数,我们可以用全部展平的方式,然后拿到展平数组长度即可。

      function flatData(arr, newArr: any = []) {
        //递归展平数据,统计数量
        if (arr && Array.isArray(arr)) {
          for (const item of arr) {
            if (item.children) {
              this.flatData(item.children, newArr);
            } else {
              newArr.push(item);
            }
          }
        }
      }
    

    统计每一级的个数

    如果统计每一级的个数,注意要把非叶子节点排除掉。

     function  getLeafCount(arr, lastItem: any = null) { //累加结果
    
        if (arr && Array.isArray(arr)) {
          for (const item of arr) {
            if (item.children) {
              if (!item.count) {
                item.count = 0;
                
              }
              
              item.count += (item.children.filter(v=>v.isLeaf)).length;
              if (lastItem && lastItem.count) {
                lastItem.count += item.count;
              }
    
              this.getLeafCount(item.children, item);
            }
          }
        }
      }
    

    相关文章

      网友评论

          本文标题:如何统计tree每一级的个数?

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