let arr = [
{
name: '1',
subtype: 'abc',
subtype1: 'abc'
},
{
name: '1',
subtype: 'qwe',
subtype1: 'abc'
},
{
name: '2',
subtype: '123',
subtype1: 'abc'
},
{
name: '2',
subtype: '345',
subtype1: 'abc'
},
{
name: '3',
subtype: 'asd',
subtype1: 'abc'
},
{
name: '3',
subtype: 'asd',
subtype1: 'abc'
},
{
name: '4',
subtype: 'asd',
subtype1: 'abc'
}
]
/**
* 根据数组对象某个相同的关键字,合并其余选项
*
* @param {Array} array 原始数据
* @returns 合并的新数组
*/
function mergeArrayInObject(array) {
let tempArray = []
let newArray = []
array.forEach((a, i) => {
if (array[i + 1] && array[i]['name'] == array[i + 1]['name']) {
tempArray.push(a)
} else {
let item = {}
tempArray.forEach(t => (item = { ...item, ...t }))
newArray.push(item)
tempArray = []
}
})
return newArray
}
console.log(mergeArrayInObject(arr))
结果
[
{ name: '1', subtype: 'abc', subtype1: 'abc' },
{ name: '2', subtype: '123', subtype1: 'abc' },
{ name: '3', subtype: 'asd', subtype1: 'abc' },
{ name: '3', subtype: 'asd', subtype1: 'abc' }
]