要根据 id 和 itemid 将数组2合并到数组1中,
我们可以遍历数组2,
然后在数组1中查找具有相同 id和 itemid 的元素。
如果找到匹配项,我们可以将数组2中的相关对象合并到数组1的对应对象中。
如果没有找到匹配项,我们可以将数组2中的对象添加到数组1中。
const array1 = [
{ id: 1, itemid: 101, name: 'Item A' },
{ id: 2, itemid: 102, name: 'Item B' },
{ id: 3, itemid: 103, name: 'Item C' }
];
const array2 = [
{ id: 1, itemid: 101, description: 'Description for Item A' },
{ id: 2, itemid: 102, price: 10.99 },
{ id: 4, itemid: 104, name: 'Item D', description: 'Description for Item D' }
];
// 遍历数组2,根据id和itemid合并到数组1中
for (const item2 of array2) {
const foundIndex = array1.findIndex(item1 => item1.id === item2.id && item1.itemid === item2.itemid);
if (foundIndex !== -1) {
// 如果找到匹配项,则合并对象
Object.assign(array1[foundIndex], item2);
} else {
// 如果没有找到匹配项,则添加新对象到数组1
array1.push(item2);
}
}
console.log(array1);
输出结果
[
{
"id": 1,
"itemid": 101,
"name": "Item A",
"description": "Description for Item A"
},
{
"id": 2,
"itemid": 102,
"name": "Item B",
"price": 10.99
},
{
"id": 3,
"itemid": 103,
"name": "Item C"
},
{
"id": 4,
"itemid": 104,
"name": "Item D",
"description": "Description for Item D"
}
]
array2 中的第一个和第二个对象与 array1 中的对象有匹配的 id 和 itemid,所以它们被合并了。第三个对象在 array1 中没有匹配项,所以它被添加到了 array1 的末尾。
1万+

被折叠的 条评论
为什么被折叠?



