从底层到顶层的递归算法

105 阅读1分钟

不多说,直接上代码

data() {
    return {
      tree: [
        {
          children: [
            {
              children: [
                {
                  num: 200
                },
                {
                  num: 100
                }
              ]
            },
            {
              children: [
                {
                  num: 100
                }
              ]
            }
          ]
        }
      ]
    };
},

methods: {
   calField(tree) {
      tree.forEach(node => {
        if (node.children && node.children.length) {
          this.calField(node.children);
          node.num = node.children.reduce(
            (sum, item) => ((sum += item.num), sum),
            0
          );
        }
      });
      return tree;
   }
}

  • 适用场景:
    • 需要从下往上累加统计的数据,比如统计省的总数需要先统计市的总数,统计市的总数要先统计县/村。