SOURCE

/**
 * 合计数量
 * @param  {json}} data 
 * @param  {string} Type 合计的字段
 * @param  {string} childstr 节点字段
 * @returns json
 */

function getNum(data, Type, childstr) {
    let Num = 0;
    for (let i = 0; i < data.length; i++) {
        if (!data[i]['' + childstr + ''] || data[i]['' + childstr + ''].length == 0) {

        } else {
            const menuInfo = this.getNum(data[i]['' + childstr + ''], Type, childstr);
            if (menuInfo['' + Type + '']) {
                data[i]['' + Type + ''] = data[i]['' + Type + ''] + menuInfo['' + Type + ''];
            } else {
                data[i]['' + Type + ''] = data[i]['' + Type + ''];
            }
        }
        Num = Num + data[i]['' + Type + ''];
    }
    const returnData = {};
    returnData['' + Type + ''] = Num;
    return returnData;
}
let json = [{
    name: 'test1',
    id: 1,
    count:0,
    childs: [{
        name: 'test2',
        id: 2,
        count:0,
        childs: [{
            name: 'test3',
            id: 3,
            count:2,
            childs: null
        }]
    }, {
        name: 'test4',
        id: 4,
        count:3,
        childs: null
    }]
}]
getNum(json, 'count', 'childs');
console.log(json)
console 命令行工具 X clear

                    
>
console