通过匹配对象属性对多个数组进行筛选

时间:2022-12-29 20:14:03

It's easy to get rid of unmatched object property by single value, like

很容易通过单个值来除去不匹配的对象属性,比如。

const person = [
  {name:'james',gender:'male'},
  {name:'john',gender:'male'},
  {name:'chun li',gender:'female'}
]
const gender = ['male'];

let filtered = person.filter( obj => obj.gender === 'male');

console.log(filtered)

But what if the gender is both exist, like ['male', 'female']? is there any loadash method can help in this case?

但是,如果性别都存在,比如“男性”、“女性”,又会怎么样呢?在这种情况下有任何loadash方法可以帮助吗?

3 个解决方案

#1


3  

The way filter works is by simply supplying it a function that returns true for objects you would like to keep (docs). With that in mind, all you need to do is return true if the gender is either male or female.

过滤器的工作方式是简单地为它提供一个函数,该函数为您希望保留的对象返回true (doc)。考虑到这一点,你所需要做的就是在性别是男性或女性的情况下返回true。

let filtered = person.filter((entry) => {
    return (entry.gender == 'male') || (entry.gender == 'female');
})

#2


3  

Use _.includes

使用_.includes

const genders = ['male', 'female'];
let filtered = person.filter(obj => _.includes(genders, obj.gender));

#3


0  

You can also use [].indexOf to have desired outcome.

您还可以使用[]。索引具有期望的结果。

const person = [
  {name:'james', gender:'male'},
  {name:'john', gender:'male'},
  {name:'chun li', gender:'female'}
]
const gender = ['male', 'female'];

person.filter((obj) => gender.indexOf(obj.gender)> -1 );

#1


3  

The way filter works is by simply supplying it a function that returns true for objects you would like to keep (docs). With that in mind, all you need to do is return true if the gender is either male or female.

过滤器的工作方式是简单地为它提供一个函数,该函数为您希望保留的对象返回true (doc)。考虑到这一点,你所需要做的就是在性别是男性或女性的情况下返回true。

let filtered = person.filter((entry) => {
    return (entry.gender == 'male') || (entry.gender == 'female');
})

#2


3  

Use _.includes

使用_.includes

const genders = ['male', 'female'];
let filtered = person.filter(obj => _.includes(genders, obj.gender));

#3


0  

You can also use [].indexOf to have desired outcome.

您还可以使用[]。索引具有期望的结果。

const person = [
  {name:'james', gender:'male'},
  {name:'john', gender:'male'},
  {name:'chun li', gender:'female'}
]
const gender = ['male', 'female'];

person.filter((obj) => gender.indexOf(obj.gender)> -1 );