js数组内根据相同key合并,里面的数组也合并(兼容ie9/ie10浏览器)

2024年07月19日 建站教程

功能需求:在同一个数组内根据用户的名字合并(合并相同名字),里面的数组也跟着合并。具体代码如下:

数组合并

var resData = [{
  id:'11',
  name:'小米',
  count:1,
  logs:[{
    rules:'规则1',
    type:1
  },{
    rules:'规则2',
    type:2
  }]
},{
  id:'12',
  name:'小红',
  count:1,
  logs:[{
    rules:'规则2',
    type:2
  }]
},{
  id:'13',
  name:'小李',
  count:1,
  logs:[{
    rules:'规则3',
    type:1
  }]
},{
  id:'14',
  name:'小米',
  count:1,
  logs:[{
    rules:'规则4',
    type:1
  }]
}]

var tempArr = [];
var resultData = [];
for (var i = 0; i < resData.length; i++) {
  if (tempArr.indexOf(resData[i].name) === -1) {
    resultData.push({
      id: resData[i].id,
      name: resData[i].name,
      count: resData[i].count,
      logs: resData[i].logs
    });
    tempArr.push(resData[i].name);
  } else {
    for (var j = 0; j < resultData.length; j++) {
  	if (resultData[j].name == resData[i].name) {
	  var logs = resultData[j].logs.concat(resData[i].logs)
  	  resultData[j].logs = logs
  	  break;
  	}
    }
  }
}
console.log('resultData',resultData)

虽然写法有些麻烦,但是客户需求兼容ie9、ie10浏览器~

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

展开阅读全文