js 统计树形组织架构人员数量

组织架构树形数据,且存在一个人员在多公司/或部门计数重复问题

// 统计组织架构内人员数量
const countNodesProperty = (treeItemData, propertyName, propertyValue) => {
    let count = 0
    const userArr = []
    const traverse = nodes => {
        nodes.forEach(node => {
            if (node[propertyName] === propertyValue) {
                // 当前公司/部门内无此人员时,再计数。解决人员在多公司/部门时计数重复问题
                if (!userArr.find(item => item.id === node.id)) {
                    count++
                }
                userArr.push(node)
            }
            if (node.childList && node.childList.length) {
                traverse(node.childList)
            }
        })
    }
    traverse([{ ...treeItemData }])
    return count
}
// 操作树形数据
const handleTreeData() {
    // 组织架构树形数据
    const treeData= [
        {
            id: '1',
            name: '总公司',
            type: '1', // 1 公司, 2 部门,3 人员
            parentId: '0',
            childList: [
                {
                    id: '2',
                    name: '上海公司',
                    type: '1',
                    parentId: '1',
                    childList: [
                        {
                            id: '2-1',
                            name: '部门1',
                            type: '2',
                            parentId: '2',
                            childList: [
                                id: '2-1-1',
                                name: '张三',
                                type: '3',
                                parentId: '2-1',
                            ]
                        },
                        {
                            id: '2-2',
                            name: '部门2',
                            type: '2',
                            parentId: '2',
                            childList: [
                                id: '2-1-1',
                                name: '张三',
                                type: '3',
                                parentId: '2-2',
                            ]
                        },
                    ]
                }
            ]
        }
    ]
    const handeData = data => {
        data.forEach(item => {
            if (item.type !== 3) {
                item.count = countNodesProperty(item, 'type', 3)
            }
            if (item.childList && item.childList.length) {
                handeData(item.childList)
            }
        })
    }
    handeData(treeData)
}

 

posted @ 2024-11-14 11:51  hong_li  阅读(60)  评论(0)    收藏  举报