0

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...
Dorad
  • 3,413
  • 2
  • 44
  • 71
B.Adler
  • 1,499
  • 1
  • 18
  • 26
  • 1
    Simplest way is to wrap it in try catch block – Rajesh Sep 08 '22 at 06:42
  • 4
    Use [optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining). `someObject?.someKey?.otherKey?.key3?.youGetThePoint` – Ivar Sep 08 '22 at 06:44
  • @Ivar It absolutely does. Thank you very much. I guess when I was looking for the answer I didn't know how to word it properly. – B.Adler Sep 09 '22 at 07:47

1 Answers1

-1

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