I would like to simulate a C # Any () method that can be used to determine if a collection has any matching objects based on a lambda expression.
I used jQuery $. grep to simplify the task:
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('xa === 1'));
I know that eval() is bad practice for obvious reasons. But is it normal in this case, since I will not use it with anything related to some user inputs?
Can this be done without eval() ? I cannot figure out a way to pass an expression to a function without evaluating it.
http://jsfiddle.net/dgGvN/
Johan source share