js 数组合并
1.简单类型数组
ES6
array1.push(...array2) // => don't remove duplication
OR
[...array1,...array2] // => don't remove duplication
OR
[...new Set([...array1 ,...array2])]; // => remove duplication
2.对象数组
(1)方法一
var initialData = [{
'ID': 1,
'FirstName': 'Sally'
},
{
'ID': 2,
'FirstName': 'Jim'
},
{
'ID': 3,
'FirstName': 'Bob'
}
];
var newData = [{
'ID': 2,
'FirstName': 'Jim'
},
{
'ID': 4,
'FirstName': 'Tom'
},
{
'ID': 5,
'FirstName': 'George'
}
];
var ids = new Set(initialData.map(d => d.ID));
var merged = [...initialData, ...newData.filter(d => !ids.has(d.ID))];
console.log(merged);
(2)方法二
const oldData = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Mike' },
];
const newData = [
{ id: 2, name: 'Jane' },
{ id: 4, name: 'Rick' },
{ id: 5, name: 'Jim' },
];
const usersMap = new Map();
oldData.forEach(user => usersMap.set(user.id, user));
newData.forEach(user => {
const exists = usersMap.has(user.id);
if (!exists) {
usersMap.set(user.id, user);
}
})
usersMap.forEach(user => console.log(user))