How to use String representation of object propert

2019-08-24 04:40发布

问题:

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;
    }

回答1:

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);