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
3 Answers
Reset to default 4You 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)
]));