var data = [ { province: 1, index:1}, { province: 2, index:3}, { province: 1, index:3}, { province: 2, index:2} ]
想要得到的格式
{ province: 1, index:4}, { province: 2, index:5}
实现过程
方法一:
console.log(editArr(data, 'province', 'index'));
function editArr(data, repeat, merge){ // repeat: 去重的key // merge: 合并的key var currArr = [] var newArr = [] data.forEach((item,i)=>{ if(currArr.indexOf(data[i][repeat]) == -1){ newArr.push({ [repeat]: data[i][repeat], [merge]: data[i][merge] }) currArr.push(data[i][repeat]) }else{ newArr.forEach(subItem=>{ if(subItem[repeat] == data[i][repeat]){ subItem[merge] += data[i][merge] } }) } }) return newArr }
方法二:
function mergeArr(arr){ var newArr=[]; arr.forEach(item=>{ var dataItem =item if(newArr.length>0){ var filterValue = newArr.filter(v=>{ return v.province == dataItem.province }) if(filterValue.length>0){ newArr.forEach(n=>{ if( n.province ==filterValue[0].province){ n.index = Number(filterValue[0].index) + Number(dataItem.index) } }) }else{ newArr.push(dataItem) } }else{ newArr.push(dataItem) } }) return newArr }
调用
mergeArr(data)