I would like to simulate the C# Any() method, which can be used to determine whether if a collection has any matching objects based on a lambda expression.
I used jQuery's $.grep to make things easier:
Array.prototype.any = function (expr) {
if (typeof jQuery === 'undefined')
throw new ReferenceError('jQuery not loaded');
return $.grep(this, function (x, i) {
return eval(expr);
}).length > 0;
};
var foo = [{ a: 1, b: 2 }, { a:1, b: 3 }];
console.log(foo.any('x.a === 1')); //true
console.log(foo.any('x.a === 2')); //false
I know that eval()
is bad practice for obvious reasons. But is it ok in this case, since I won't use this with anything related to some user inputs?
Can this be done without eval()
? I can't figure out a way to pass an expression to the function without evaluating it.