DEV Community

Ali
Ali

Posted on

Right way to test (deep) nested JS objects for undefined properties

Problem: What is the best optimal way to test (deep) nested objects for undefined properties apart from

if(test.level1 && test.level1.level2 && test.level1.level2.level3) {
    alert(test.level1.level2.level3);
} 

:)
Solution: Suppose this is our deep nested object

var test = {level1: {level2: {level3: "level3"}}};

Most performant way is as per this writing and if you have not upgraded to ECMAScript 2020 Standard.

var level3 = (((test || {}).level1 || {}).level2 || {}).level3;
alert( level3 );

In ECMAScript 2020 standard this can be done as this

const value = obj?.level1?.level2?.level3 

For complete discussion please see stackoverflow original article below:
https://stackoverflow.com/questions/2631001/test-for-existence-of-nested-javascript-object-key/4034468#4034468
Note: For above custom solution test should be defined and also it might not work if properties are booleans.

Top comments (0)