发布于 5年前

如何把一个带有相同元素值的数组归类组成一个新的二维数组?

相关代码

    let arr = [{
            code: "China",
            name: "xiaohuai"
        },
        {
            code: "Africa",
            name: "neiLuoBi"
        },
        {
            code: "Asia",
            name: "hanGuo"
        },
        {
            code: "China",
            name: "tnnyang"
        },
        {
            code: "Africa",
            name: "nanFei"
        },
        {
            code: "China",
            name: "yangMan"
        }
    ]

归类为下面这种形式

    let arr2 = [{
        China: [{
                name: "xiaohuai"
            },
            {
                name: "tnnyang"
            },
            {
                name: "yangMan"
            }
        ],
        Africa: [{
                name: "neiLuoBi"
            },
            {
                name: "nanFei"
            }
        ],
        Asia: [{
            name: "hanGuo"
        }]
    }]

解决方案

let result = arr.reduce((result, item) => {
    let data = {name: item.name}
    result[item.code] ? result[item.code].push(data) : (result[item.code] = [data]);
    return result
}, Object.create(null));

result = [result]
©2020 edoou.com   京ICP备16001874号-3