最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Filter with multiple values with lodash? - Stack Overflow

programmeradmin4浏览0评论

I can filter with:

let users = [{'name': 'john', 'age': '20'},{'name': 'jeff', 'age': '2'}

_.filter(users, { 'name': 'john', 'age': '20');

The above will get the user john, but how can I specify multiple options for each array?

For example, I want to get people called john and jeff who are aged 20, something like:

_.filter(users, { 'name': 'john' | 'jeff', 'age': '20');

How can I do this with lodash?

I can filter with:

let users = [{'name': 'john', 'age': '20'},{'name': 'jeff', 'age': '2'}

_.filter(users, { 'name': 'john', 'age': '20');

The above will get the user john, but how can I specify multiple options for each array?

For example, I want to get people called john and jeff who are aged 20, something like:

_.filter(users, { 'name': 'john' | 'jeff', 'age': '20');

How can I do this with lodash?

Share Improve this question asked Jan 31, 2018 at 19:49 panthropanthro 24.1k70 gold badges205 silver badges350 bronze badges 1
  • Does this answer your question? lodash filter on key with multiple values – Étienne Commented Jun 2, 2021 at 8:42
Add a ment  | 

3 Answers 3

Reset to default 4

You can use a function as the second argument:

_.filter(users, obj => (obj.name == 'john' || obj.name == 'jeff') && obj.age == '20'));
var arr = ['barney','fred']
_.filter(users, (user) => {
  // You can put the required conditions here.
  return arr.indexOf(user.user) >=0 && user.age > '20';

});

This is one way to do it where you can specify any conditions. Since you have array of required names, you can do it for multiple names and you can do the same with age.

another flexible solution, just add conditions:

const res = _.filter(users, ({ name, age }) => _.every([
    _.includes(['john', 'jeff'], name),
    _.includes(['20'], age)
]));
发布评论

评论列表(0)

  1. 暂无评论