根据对象某个key包含其他key切割并分组

        const dataList = [{
            "id": "4028e300786db35b01786db747720002",
            "title": "专家职称",
            "name": "张飞",
            "birthday": "1970-01-13",
            "sex": "1",
            "department": "儿科",
        },
        {
            "id": "4028e300786db35b01786db747720003",
            "title": "专家职称",
            "name": "关羽",
            "birthday": "1970-01-13",
            "sex": "1",
            "department": "神经外科",
        },
        {
            "id": "4028e300786db35b01786db747720004",
            "title": "专家职称",
            "name": "刘备",
            "birthday": "1970-01-13",
            "sex": "1",
            "department": "普通外科",
        },
        {
            "id": "4028e300786db35b01786db747720005",
            "title": "专家职称",
            "name": "诸葛亮",
            "birthday": "1970-01-13",
            "sex": "1",
            "department": "普通外科$儿科",  //诸葛亮既属于 普通外科$儿科
        }
    ]

    //将普通外科$儿科切割出来,形成一个新的对象
    const result = {
        data: dataList.reduce((res, item) => res.concat(...item.department.split('$').map(b => ({
            ...item,
            b
        }))), []),
    };
    
    //此时result:[儿科,神经外科,普通外科,儿科,普通外科],然后数组对象根据某个key相同合并分组
    function resultList(result) {
        // console.log(result)
        let obj = {};
        result.forEach((item, index) => {
            let {b} = item;
            if (!obj[b]) {
                obj[b] = {
                    b,
                    data: []
                }
            }
            obj[b].data.push(item);
        })
        let data = Object.values(obj)
        console.log(data)
    }
    resultList(result.data)

最终想要的理想数据

image.png

你可能感兴趣的:(根据对象某个key包含其他key切割并分组)