假设我们有两个对象数组,其中第一个包含一些带有用户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' } ]