js数组根据相同key合并并把id转数组输出

2024年07月29日 建站教程

最终格式:

var logs = [{
	examNos:["200904760062"],
	id: "809bd3003dba",
},{
	examNos:["200904760062","200904760060"],
	id: "809bd3003dba1111",
},{
	examNos:["200904760062","200904760060"],
	id: "809bd3003dba",
}]
//修改examNo数组格式
var otherUnionLogs = []
for(var i=0; i<logs.length; i++){
	if(logs[i].examNos.length == 1){
		otherUnionLogs.push({
			examNo: logs[i].examNos.toString(),
			ruleId: logs[i].id.toString()
		})
	}else{
		for(j=0; j<logs[i].examNos.length; j++){
			otherUnionLogs.push({
				examNo: logs[i].examNos[j],
				ruleId: logs[i].id.toString()
			})
		}
	}
}
console.log('otherUnionLogs',otherUnionLogs)
//根据相同examNo合并
var beforeData = otherUnionLogs;
let tempArr = [];
let afterData = [];//新数组
for (let i = 0; i < beforeData.length; i++) {
	if (tempArr.indexOf(beforeData[i].examNo) === -1) {
	  afterData.push({
		examNo: beforeData[i].examNo,
		ruleId: [beforeData[i].ruleId]
	  });
	  tempArr.push(beforeData[i].examNo);
	} else {
	  for (let j = 0; j < afterData.length; j++) {
		if (afterData[j].examNo == beforeData[i].examNo) {
		  afterData[j].ruleId.push(beforeData[i].ruleId);
		  break;
		}
	  }
	}
}
console.log(afterData,'afterData')

本文链接:http://so.lmcjl.com/news/9429/

展开阅读全文