DEV Community

Ali
Ali

Posted on

3

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.

Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil — patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

Top comments (0)

Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup 🚀

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

👋 Kindness is contagious

Dive into this insightful write-up, celebrated within the collaborative DEV Community. Developers at any stage are invited to contribute and elevate our shared skills.

A simple "thank you" can boost someone’s spirits—leave your kudos in the comments!

On DEV, exchanging ideas fuels progress and deepens our connections. If this post helped you, a brief note of thanks goes a long way.

Okay