1

I have in many places in my code the following format:

if (a && a.b && a.b.c && a.b.c.d) {
    //do something with a.b.c.d
}

Given a,b,c and d have a more complex names this is very ugly, time consuming and open places for mistakes.

Is there a "sugarcoating" for this, something like:

if (valid(a.b.c.d)) {
    //do something with a.b.c.d
}
Roee Gavirel
  • 18,955
  • 12
  • 67
  • 94

1 Answers1

2

You can make recursive helper function to do this, for example:

function valid(obj, chain) {
    if (!chain.length) {
        return true;
    }
    var prop = chain.shift();
    return !obj.hasOwnProperty(prop) ? false : valid(obj[prop], chain);
}

var a = { b: { c: { d: 1 } } };

console.log(valid(a, ['b', 'c', 'd'])); // true
console.log(valid(a, ['b', 'c', 'e'])); // false
madox2
  • 49,493
  • 17
  • 99
  • 99