JavaScript——根据 id 属性合并两个数组
假设我们有两个对象数组,第一个数组包含某些包含用户 ID 和用户名的对象。
该数组包含包含用户 ID 和用户地址的对象。
该数组是 -
const arr1 = [ {"id":"123","name":"name 1"}, {"id":"456","name":"name 2"} ]; const arr2 = [ {"id":"123","address":"address 1"}, {"id":"456","address":"address 2"} ];
需要编写一个 JavaScript 函数,该函数采用两个这样的数组并将这两个数组合并形成第三个数组。
第三个数组应包含相应用户的用户 ID、姓名和地址对象。
实例
代码如下 -
const arr1 = [ {"id":"123","name":"name 1"}, {"id":"456","name":"name 2"} ]; const arr2 = [ {"id":"123","address":"address 1"}, {"id":"456","address":"address 2"} ]; const mergeArrays = (arr1 = [], arr2 = []) => { let res = []; res = arr1.map(obj => { const index = arr2.findIndex(el => el["id"] == obj["id"]); const { address } = index !== -1 ? arr2[index] : {}; return { ...obj, address }; }); return res; }; console.log(mergeArrays(arr1, arr2));
输出
控制台输出如下 -
[ { id: '123', name: 'name 1', address: 'address 1' }, { id: '456', name: 'name 2', address: 'address 2' } ]
广告