In javascript is there a way to write a conditional on the property of an object several layers deep without checking each layer?

Viewed 28

I have an object:

let someObject = {
  someKey: {
    otherKey: {
      key3: {
         youGetThePoint: null
      }
    }
  }
};

If I write:

if (someObject.someKey.otherKey.key3.youGetThePoint) {
   doStuff();
}

and some method removes key3 from the object in otherKey then this conditional breaks.

Is there a way to write this conditional without linking several && together or nesting several conditionals to check each layer? i.e. avoiding:

if (someObject && someObject.someKey && some...
1 Answers

let someObject = {
  someKey: {
    otherKey: {
      key3: {
         youGetThePoint: null
      }
    }
  }
};
function objNestedCheck(someObject, someKey, otherKey, key3, youGetThePoint) {
  var args = Array.prototype.slice.call(arguments, 1);

  for (var i = 0; i < args.length; i++) {
    if (!someObject|| !someObject.hasOwnProperty(args[i])) {
      return false;
    }
    someObject= someObject[args[i]];
  }
  return true;
}

objNestedCheck(someObject , 'someKey', 'otherKey', 'key3', 'youGetThePoint');

if (objNestedCheck(someObject , 'someKey', 'otherKey', 'key3', 'youGetThePoint')) {
  // you can do your stuff here 
  doStuff();
}

using ES6 features and recursion

function checkNested(someObject , someKey,  ...rest) {
  if (someObject === undefined) return false
  if (rest.length == 0 && someObject .hasOwnProperty(someKey)) return true
  return checkNested(someObject [level], ...rest)
}
if (checkNested(someObject , someKey,  ...rest)) {
      // you can do your stuff here 
      doStuff();
}
Related