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*/
        }
    }
}
1
  • 2
    Please be aware that json_root.hasOwnProperty means that you're not dealing with JSON, but a regular JS object. Commented Mar 7, 2022 at 8:39

1 Answer 1

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.