0

I'd like to check the existence of a nested js object property, any way to simplify this code in one line?

if(json_root.hasOwnProperty(p1)){
    if(json_root.p1.hasOwnProperty(p2)){
        if(json_root.p1.p2.hasOwnProperty(p3)){
            /**Do your things with json_root.p1.p2.p3*/
        }
    }
}
Manu Ruiz Ruiz
  • 373
  • 1
  • 2
  • 11

1 Answers1

1

You can just define a if statement like this

if(json_root.p1 && json_root.p1.p2 && json_root.p1.p2.p3){
    // Here add your code
}

The block code of the if statement will be executed only when all three condition are valid.

Yves Kipondo
  • 5,289
  • 1
  • 18
  • 31