1. 程式人生 > >js物件根據某個共同欄位分組

js物件根據某個共同欄位分組

 

var data = [
    {key: "9876", value: "1527"}
    {key: "9876", value: "1528"}
    {key: "9877", value: "1529"}
]

var map = {},
dest = [];
for(var i = 0; i < data.length; i++){
    var ai = data[i];
    if(!map[ai.key]){
        dest.push({
            key: ai.key,
            value: [ai.value]
        });
        map[ai.key] = ai;
    }else{
        for(var j = 0; j < dest.length; j++){
            var dj = dest[j];
            if(dj.key == ai.key){
                dj.value.push(ai.value);
                break;
            }
        }
    }
}

console.log(dest);