如何使用另一个对象数组中的名称过滤对象数组 [英] How to filter an array of objects with names from another array of objects
本文介绍了如何使用另一个对象数组中的名称过滤对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Java的新手,我在如何使用地图,过滤器,查找和其他功能方面苦苦挣扎.我有两个对象数组,我想用第二个对象过滤第一个对象.
I'm new to Javascript and I'm struggling with how to use the map, filter, find and other functions. I have two arrays of objects, and I wanted to filter the first one with the second.
const users = [
{ name: 'Anna', age: 22, gender: 'F' },
{ name: 'John', age: 25, gender: 'M' },
{ name: 'Mary', age: 27, gender: 'F' },
{ name: 'Joe', age: 30, gender: 'M' }
]
const filter = [
{ name: 'Anna' },
{ name: 'John' }
]
// Here is the expected result:
const expected_result = [
{ name: 'Anna', age: 22, gender: 'F' },
{ name: 'John', age: 25, gender: 'M' }
]
有人知道这样做的最好方法是什么吗?
Does anyone know what is the best way to do this?
推荐答案
最佳方法是什么"是一个见解,但是如果您有一个较大的过滤器对象,则首先将其转换为临时集是很有意义的:
"What is the best way" is a matter of opinion, but if you would have a large filter object, then it makes sense to first convert it to a temporary set:
function filterBy(users, filter) {
let set = new Set(filter.map(({name}) => name)); // for faster lookup
return users.filter(({name}) => set.has(name));
}
// demo
const users = [{name: 'Anna',age: 22,gender: 'F',},{name: 'John',age: 25,gender: 'M',},{name: 'Mary',age: 27,gender: 'F',},{name: 'Joe',age: 30,gender: 'M',},];
const filter = [{name: 'Anna',},{name: 'John',}];
console.log(filterBy(users, filter));
这篇关于如何使用另一个对象数组中的名称过滤对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文