简体   繁体   中英

Can I use the 'in' keyword to test a property in an (tree) object

Let's say I've got the following object:

Variables.settings.backend.url = 'http://localhost';

What I would do to test is url is available, is do to the following:

if ('settings' in Variables && 'backend' in Variables.settings && 'url' in Variables.settings.backend) {
  // true
}

This is quite cumbersome.

If this was PHP, i could just do

if (!empty($variables['settings']['backend']['url']) {
  //true
}

Can this be done any simpler in JS?

I wrote a function to test this :

var isModuleDefined = function(moduleName) {
    var d = moduleName.split(".");
    var md = d[0];
    for (var i = 1, len = d.length; i <= len; i++) {
        if (eval("typeof " + md) !== "undefined") {
            md = md + "." + d[i];
            continue;
        }
        break;
    }
    return i === len + 1;
};

isModuleDefined("Variables.settings.backend.url");

but i really don't know about the cost-efficiency of that method, using eval.

Edit (Without eval..):

var isModuleDefined = function(moduleName) {
    var d = moduleName.split(".");
    var base = window;
    for (var i = 0, len = d.length; i < len; i++) {
        if (typeof base[d[i]] != "undefined") {
            base = base[d[i]];
            continue;
        }
        break;
    }
    return i === len;
};

Yet another variant

function isFieldExist(expression){
    var fields = expression.split('.'),
        cur = this;

    for(var i=0; i<fields.length; i++){
        if(typeof cur[fields[i]] === "undefined") return false;
        cur = cur[fields[i]];
    }
    return true;    
}

for using

isFieldExist("Variables.settings.backend.url"); // find in global scope

isFieldExist.call(Variables, "settings.backend.url"); // find in Variables

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM