0

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?

sbrattla
  • 5,274
  • 3
  • 39
  • 63

2 Answers2

2

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;
};
Hacketo
  • 4,978
  • 4
  • 19
  • 34
  • 1
    [eval](http://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea)? – Grundy Sep 22 '14 at 11:51
2

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
Grundy
  • 13,356
  • 3
  • 35
  • 55