如何在JavaScript中将两个数组与一个对象合并?
假设我们有两个这样的对象数组-
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函数,该函数接受两个这样的数组并返回一个新数组。
新数组应包含第一个数组和第二个数组的所有唯一对象。在这里,要检查任何对象的唯一性,我们将检查其唯一的“名称”属性。
示例
为此的代码将是-
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' }
]
以上是 如何在JavaScript中将两个数组与一个对象合并? 的全部内容, 来源链接: utcz.com/z/316084.html