0

Take the code below, is there an easier/better way to check for the existence of myProp3? Imagine that myProp1 and myProp2 also only exist if myProp3 exists. I have run into a few API's that do this and it's a bear to check for the existence of these sub properties down a long chain.

var myObj = {
    myProp1: {
        myProp2: {
            myProp3: 'myProp3'
        }
    }
}

if (myObj.myProp1 && myObj.myProp1.myProp2 && myObj.myProp1.myProp2.myProp3 && myObj.myProp1.myProp2.myProp3 == 'myProp3') {
    //do something
}
skinneejoe
  • 3,921
  • 5
  • 30
  • 45
  • Thanks, I tried searching for the answer but couldn't find it. But that duplicate answer does answer my question. – skinneejoe Oct 02 '15 at 14:52
  • Just notice that the dup is not solving an array case. ( for example if myprop2 is an array whose second argument is an object who has myprop3. – Royi Namir Oct 02 '15 at 15:39
  • True, but one of the answers on the page references the _.get() method for lodash, which according to the documentation appears to handle arrays like so: _.get(object, 'a[0].b.c'); – skinneejoe Oct 02 '15 at 19:08

0 Answers0