I have an array of objects
var arr = [{a:1},{a:5}, {a:6},{a:11}];
I want to use underscore find where function to retrieve object satisfying condition a = 1
or a =11
like:
_findWhere(arr, {a:1} || {a:11})
Anything like this is possible ??
find behaves like findWhere in that it returns the first item that passes the search criteria. With find you can use a predicate to specify the search criteria.
var result = _.find(arr, function(item) {
return item.a == 1 || item.a == 11;
});
you can use _.filter for this
var arr = [{a:1}, {a:5}, {a:6}, {a:11}];
_.filter(arr,function(n){return (n.a===1 || n.a===11)});
But there is a better solution which can help you adding as many or as you want. Using _.mixin you can create your own or function
var arr = [{a:1}, {a:5}, {a:6}, {a:11}];
_.mixin({
or: function(obj,arr,condition){
return _.chain(arr).where(condition).union(obj).value();
}
});
_.chain(arr).where({a:1}).or(arr,{a:11}).or(arr,{a:2}).value();//returns 2 objects
_.chain(arr).where({a:1}).or(arr,{a:11}).or(arr,{a:5}).value();//returns 3 objects
_.chain(arr).where({a:1}).or(arr,{a:11}).value();//returns 2 objects
var arr2 = [{a:1,b:4}, {a:5}, {a:6}, {a:11}];
_.chain(arr2).where({a:1}).or(arr2,{a:11}).value();//returns 2 objects
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With