gpt4 book ai didi

javascript - 合并/替换数组中具有相同 ID 的对象

转载 作者:行者123 更新时间:2023-12-02 21:58:24 25 4
gpt4 key购买 nike

我有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);

关于javascript - 合并/替换数组中具有相同 ID 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59944843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com