如何在 JavaScript 中将两个带有对象的数组合并为一个?
javascriptweb developmentfront end technologyobject oriented programming
假设我们有两个像这样的对象数组 −
const arr1 = [ {name:'test', lastname: 'test', gender:'f'}, {name:'test1', lastname: 'test1', gender:'f'}, {name:'test2', lastname: 'test2', gender:'m'} ]; const arr2 = [ {name:'test21', lastname: 'test21', gender:'f'}, {name:'test1', lastname: 'test1', gender:'f'}, {name:'test2', lastname: 'test2', gender:'m'}, {name:'test22', lastname: 'test22', gender:'m'} ];
这些数组中没有任何重复的对象(根据 'name' 属性重复),但第一个和第二个对象中存在一些具有重复名称的对象。
我们需要编写一个 JavaScript 函数,该函数接受两个这样的数组并返回一个新数组。
新数组应包含第一个和第二个数组的所有唯一对象。在这里,要检查任何对象的唯一性,我们将检查其唯一的"name"属性。
示例
其代码为 −
const arr1 = [ {name:'test', lastname: 'test', gender:'f'}, {name:'test1', lastname: 'test1', gender:'f'}, {name:'test2', lastname: 'test2', gender:'m'} ]; const arr2 = [ {name:'test21', lastname: 'test21', gender:'f'}, {name:'test1', lastname: 'test1', gender:'f'}, {name:'test2', lastname: 'test2', gender:'m'}, {name:'test22', lastname: 'test22', gender:'m'} ]; const mergeUniquely = (arr1 = [], arr2 = []) => { const newArr = arr1.concat(arr2); const map = {}; const res = []; newArr.forEach(el => { if(!map[el['name']]){ res.push(el); map[el['name']] = 1; }; }); return res; }; console.log(mergeUniquely(arr1, arr2));
输出
控制台中的输出将是 −
[ { name: 'test', lastname: 'test', gender: 'f' }, { name: 'test1', lastname: 'test1', gender: 'f' }, { name: 'test2', lastname: 'test2', gender: 'm' }, { name: 'test21', lastname: 'test21', gender: 'f' }, { name: 'test22', lastname: 'test22', gender: 'm' } ]