js-获取树结构的长度

2021-06-10  本文已影响0人  汀上
<!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>
上一篇下一篇

猜你喜欢

热点阅读