function fireDuplicate (arr) { var arr = JSON.parse(JSON.stringify(arr)) var ids = [] arr.forEach(function(item) { ids.push(item.id) }) var newIds = [] var newArr = [] ids.forEach(function(id,index) { var obj = { id: '', options: [] } if (newIds.indexOf(id) > -1) { var temp = newArr.find(function(item) { return item.id == id }) temp.options.push(arr[index].options[0]) } else { obj.id = id obj.options.push(arr[index].options[0]) newIds.push(id) newArr.push(obj) } }) return newArr }
例如原始数据:
const data = [ { id: 1, content: [ {name: 'peng'} ] }, { id: 2, content: [ {name: 'xing'} ] }, { id: 1, content: [ {name: 'yuan'} ] }, ]
输出结果:
const data = [ { id: 1, content: [ {name: 'peng'}, {name: 'yuan'} ] }, { id: 2, content: [ {name: 'xing'} ] }, ]
如果你有更好的方法实现,欢迎赐教,?