<script>
var examViewList = [{
"examItemIds" : 221,
"timePoint" : "20"
}, {
"examItemIds" : 240,
"timePoint" : "40"
}, {
"examItemIds" : 221,
"timePoint" : "30"
}, {
"examItemIds" : 220,
"timePoint" : "30"
}, {
"examItemIds" : 222,
"timePoint" : "40"
}, {
"examItemIds" : 222,
"timePoint" : "40"
}
];
/**
*
* 参数:obj 传入对象
* mainKey 主键
* key 需要合并的键值名称
* flag 合并是否需要去重
*/
function objSwitch(obj, mainKey, key,flag) {
if( typeof Array.indexOf !== ‘function‘ ){
Array.prototype.indexOf = function(args){
var index = -1;
for(var i=0,l=this.length; i<l; i++){
if(this[i] === args){
index = i;
break;
}
}
return index;
}
}
var rObj = []; //返回的数组
var rObjHasMainKey = []; //返回数组包含的主键值
var i = obj.length;
while (obj[--i]){
var rIndex = rObjHasMainKey.indexOf(obj[i][mainKey]);
if(rIndex == -1){
var tempObj={};
rObjHasMainKey.push(obj[i][mainKey]);
tempObj[mainKey] = obj[i][mainKey];
tempObj[key] = [obj[i][key]];
rObj.push(tempObj);
}else{//如果已经存在的话,直接写入到返回的obj里
if(flag==true ){
if(rObj[rIndex][key].indexOf(obj[i][key])==-1){
rObj[rIndex][key].push(obj[i][key]);
}
}else{
rObj[rIndex][key].push(obj[i][key]);
}
}
}
console.log(rObj);
}
objSwitch(examViewList,‘timePoint‘,‘examItemIds‘)
</script>