[英]Merge item in array of object with the same ID on Javascript
[英]Merge / Replace object in array with same Id
我有2个数组,我尝试根据它们的id合并2个数组,并且数组的顺序必须与第一个数组相同
array1: [
{id: student1, name: 'Jacky', course: ''},
{id: student2, name: 'Taylor', course: ''},
{id: student3, name: 'David', course: ''},
{id: student4, name: 'Aisy', course: ''},
{id: student5, name: 'Micky', course: ''}
];
和
array2: [
{id: student1, name: 'Jacky', course: 'science'},
{id: student2, name: 'Taylor', course: 'biology'},
{id: student1, name: 'Jacky', course: 'math'},
{id: student4, name: 'Aisy', course: 'chemistry'},
{id: student1, name: 'Jacky', course: 'history'},
];
我希望结果像
array:[
{id: student1, name: 'Jacky', course: 'science'},
{id: student1, name: 'Jacky', course: 'math'},
{id: student1, name: 'Jacky', course: 'history'},
{id: student2, name: 'Taylor', course: 'biology'},
{id: student3, name: 'David', course: ''},
{id: student4, name: 'Aisy', course: 'chemistry'},
{id: student5, name: 'Micky', course: ''}
];
你可以这样做:
const result = [];
array1.forEach(a1 => {
result.push(a1);
array2.forEach(a2 => {
if (a1.id === a2.id) {
result.push(a2);
}
});
});
或只有一行代码:
const result =([...array1,...array2]).sort((a, b) => a.id - b.id);
最后根据上面的参考,我找到了一种适合我的情况的方法
let _newArray = [];
array1.forEach(element => {
const temp = array2.filter(x => x.id === element.id);
const temp2 = temp.filter(
x => !_newArray.find(y => y.id === x.id && y.name === x.name)
);
if (temp.length > 0) {
_newArray = [..._newArray, ...temp2];
} else {
_newArray.push(element);
}
});
console.log(_newArray);
您可以将reduce
、 filter
方法与spread syntax
结合使用。
var array1 = [ {id: 1, name: 'Jacky', course: ''}, {id: 2, name: 'Taylor', course: ''}, {id: 3, name: 'David', course: ''}, {id: 4, name: 'Aisy', course: ''}, {id: 5, name: 'Micky', course: ''} ], array2= [ {id: 1, name: 'Jacky', course: 'science'}, {id: 2, name: 'Taylor', course: 'biology'}, {id: 1, name: 'Jacky', course: 'math'}, {id: 4, name: 'Aisy', course: 'chemistry'}, {id: 1, name: 'Jacky', course: 'history'}, ]; let arr = array1.reduce((arr, item) => { let itemsFromSecondArray = array2.filter(({id}) => id == item.id); if(itemsFromSecondArray.length){ arr.push(...itemsFromSecondArray); } else arr.push(item); return arr; }, []); console.log(arr);
您可能需要使用spread 、 filter和forEach功能。
let array1 = [ {id: 1, name: 'Jacky', course: ''}, {id: 2, name: 'Taylor', course: ''}, {id: 3, name: 'David', course: ''}, {id: 4, name: 'Aisy', course: ''}, {id: 5, name: 'Micky', course: ''} ] let array2 = [ {id: 1, name: 'Jacky', course: 'science'}, {id: 2, name: 'Taylor', course: 'biology'}, {id: 1, name: 'Jacky', course: 'math'}, {id: 4, name: 'Aisy', course: 'chemistry'}, {id: 1, name: 'Jacky', course: 'history'}, ] let r = []; array1.forEach(course => { let arr = array2.filter(c => c.name === course.name); if (arr.length > 0) { r = [...r, ...arr]; } else { r.push(course) } }); console.log(r);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.