js-获取树结构的长度

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>

<script>

    let a =[{
    "code": "202",
    "name": "销售组",
    "id": 8959,
    "type": 1,
    "personNumer": 2,
    "parentId": 0,
    "selected": null,
    "subUserGroupList": [{
        "code": "202000",
        "name": "一级部门2",
        "id": 9086,
        "type": 1,
        "personNumer": 0,
        "parentId": 8959,
        "selected": null,
        "subUserGroupList": [],
        "customerUserGroupContentDTOS": null
    }, {
        "code": "202001",
        "name": "一级部门",
        "id": 9087,
        "type": 1,
        "personNumer": 0,
        "parentId": 8959,
        "selected": null,
        "subUserGroupList": [{
            "code": "202001000",
            "name": "一级部门1",
            "id": 9088,
            "type": 1,
            "personNumer": 0,
            "parentId": 9087,
            "selected": null,
            "subUserGroupList": [],
            "customerUserGroupContentDTOS": null
        }],
        "customerUserGroupContentDTOS": null
    }]
}];

    function getListlength(arr, type) {
        let num = 0;
        function getlength(arr, type) {
            num += arr.length;
            arr.forEach((ele, i) => {
                let next = arr[i][type];
                if (next.length > 0) {
                    num += next.length;

                    next.forEach((ele, j) => {
                        getlength(next[j][type], type, num)
                    })
                }
            });
        }
        getlength(arr, 'subUserGroupList')
        return num
    }

    console.log(getListlength(a, 'subUserGroupList')) ; //4

</script>

</html>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容