我有2个数组,两个数组的值都为p_id
,我想检查p_id
相同的两个数组,然后将数组2 id
添加到数组1中使用JavaScript。
Array1 = [{id:1, p_id:222}, {id:2, p_id:444}];
Array2 = [{id:121, p_id:222}, {id:212, p_id:444}];
预期结果:
Array1 = [{id:1, p_id:222, A2_id:121}, {id:2, p_id:444, A2_id:212}];
答案 0 :(得分:2)
使用try catch
:
const a1 = [{id:1, p_id:222}, {id:2, p_id:444}];
const a2 = [{id:121, p_id:222}, {id:212, p_id:444}];
a1.forEach(e => {
try {
e.A2_id = a2.find(c => c.p_id === e.p_id).id
} catch {}
})
console.log(a1);