var arr=[ {a:3,b:4}, {a:3,b:7}, {a:5,b:2}, {a:5,b:1} ]
怎樣合並為
var arr=[ {a:3,b:4,7}, {a:5,b:2,1} ]
<script>
var arr=[{a:3,b:4}, {a:3,b:7}, {a:5,b:2}, {a:5,b:1}];
var tempMap={};
for(var i=0;i<arr.length;i++){
var obj = arr[i];
var key = obj["a"];
if(tempMap[key]!=0&&!tempMap[key]){
tempMap[key]=obj["b"];
}else{
tempMap[key]=tempMap[key]+","+obj["b"];
}
}
var arrM=[];
for(key in tempMap){
arrM.push({a:key,b:tempMap[key+'']});
}
for(i=0;i<arrM.length;i++){
alert(arrM[i]['a']+"---"+arrM[i]['b']);//arrM是結果數組
}
</script>