其他分享
首页 > 其他分享> > JS - 对象数组根据key重新分组

JS - 对象数组根据key重新分组

作者:互联网

var arr = [
    { "id": "1001", "name": "值1", "value": "111" },
    { "id": "1001", "name": "值1", "value": "11111" },
    { "id": "1002", "name": "值2", "value": "25462" },
    { "id": "1002", "name": "值2", "value": "23131" },
    { "id": "1002", "name": "值2", "value": "2315432" },
    { "id": "1003", "name": "值3", "value": "333333" }
];

function getArrWithKey(originalArr, field) {
    let tempArr = [];
    let endData = [];
    for (let i = 0; i < originalArr.length; i++) {
        if (tempArr.indexOf(originalArr[i][field]) === -1) {
            endData.push({
                [field]: originalArr[i][field],
                data: [originalArr[i]]
            });
            tempArr.push(originalArr[i][field]);
        } else {
            for (let j = 0; j < endData.length; j++) {
                if (endData[j][field] == originalArr[i][field]) {
                    endData[j].data.push(originalArr[i]);
                    break;
                }
            }
        }
    }
    return endData // 最终输出
}

let a = getArrWithKey(arr, 'name');
console.log(a);

结果

[{
    "name": "值1",
    "data": [{
        "id": "1001",
        "name": "值1",
        "value": "111"
    },
    {
        "id": "1001",
        "name": "值1",
        "value": "11111"
    }]
},
{
    "name": "值2",
    "data": [{
        "id": "1002",
        "name": "值2",
        "value": "25462"
    },
    {
        "id": "1002",
        "name": "值2",
        "value": "23131"
    },
    {
        "id": "1002",
        "name": "值2",
        "value": "2315432"
    }]
},
{
    "name": "值3",
    "data": [{
        "id": "1003",
        "name": "值3",
        "value": "333333"
    }]
}]

标签:endData,originalArr,name,value,JS,field,分组,key,id
来源: https://blog.csdn.net/iotjin/article/details/119107936