gpt4 book ai didi

javascript - 比较两个对象数组与键,如果没有找到,则将其添加到数组中

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

array1 =  [
{id: 1, height: 178}, {id: 1, height: 176},
{id: 2, height: 168},{id: 2, height: 164}
]

array2 = [
{id: 1, height: ''},{id: 1, height: ''},
{id: 2, height: ''},{id: 2, height: ''},
{id: 3, height: ''}, {id: 3, height: ''},
{id: 4, height: ''}, {id: 4, height: ''}
]

resultArray = [
{id: 1, height: 178},{id: 1, height: 176},
{id: 2, height: 168},{id: 2, height: 164},
{id: 3, height:''}, {id: 3, height: ''},
{id: 4, height: ''}, {id: 4, height: ''}
]

我希望将 array1 的 id 与 array2 的 id 进行比较,如果 array1 中缺少任何对象,那么我们将其添加到该对象中大批。你能告诉我该怎么做吗?

谢谢

最佳答案

我建议使用一组 array1 的键来进行快速查找。请注意,这会改变 array1:

const array1 = [{id: 1, height: 178},{id: 1, height: 176},{id: 2, height: 168},{id: 2, height: 164}]
const array2 = [{id: 1, height: ''},{id: 1, height: ''},{id: 2, height: ''},{id: 2, height: ''}, {id: 3, height: ''}, {id: 3, height: ''}, {id: 4, height: ''}, {id: 4, height: ''}]

const ids = new Set(array1.map(e => e.id));

array2.forEach(e => {
if (!ids.has(e.id)) {
array1.push(e);
}
});

console.log(array1);

关于javascript - 比较两个对象数组与键,如果没有找到,则将其添加到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51815816/

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