0

I'm trying to use a string value of say, "[ScheduledDate] < '11/1/2011'", and test for a bool value on an object like "item". But I can't seem to be able to figure out a way to do it successfully. I'm not wanting to use the eval function, but if it's the only way, then I guess I will have to. below is an example of the function I'm trying to use.

function _filterItem2() {
        var item = { ScheduledDate: '1/1/2012' };
        var filterExpression = "[ScheduledDate] < '11/1/2011'";

        var result = item[filterExpression];  // This is where I'm not sure.

        return result;
    }
2
  • Do you control the filterExpression or is it supplied by a third party (or user)? Commented Jun 18, 2012 at 18:14
  • supplied by third party. Actually the telerik RadGrid. Commented Jun 18, 2012 at 18:50

1 Answer 1

2

No, item[filterExpression] would just return the property named like your string.

Instead, you should store your filter expression as an object:

var filter = {
    propname: "ScheduledDate",
    operator: "<",
    value: "1/1/2012"
};

Then get your comparison values:

var val1 = item[filter.propname],
    val2 = filter.value;

and now comes the tricky part. You are right, you should not use eval. But there is no possibility to get the corresponding functions from operator names, so you will need to code them yourself. You might use a switch statement or a map like this:

var operators = {
    "<": function(a,b){return a<b;},
    ">": function(a,b){return a>b;},
    ...
};
var bool = operators[filter.operator](val1, val2);
Sign up to request clarification or add additional context in comments.

2 Comments

Worked perfectly. I did two mappings, one that would use regex to get what the operator would be from the expression, and the other like the one you have above. Thanks for the help
See also here for a more dynamic approach

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.