2个数组,将值相同的一个ID加到另一个

时间:2019-10-12 19:07:29

标签: javascript arrays node.js

我有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}];

1 个答案:

答案 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);

相关问题