Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check nested JSON properties in js

I’d like to check the existence of a nested JSON 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*/
        }
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading