How to check for nested object value in a dynamic way using key variables?

Issue

If I want to check for a specific (nested) object value, I can do this by

if (configuration?.my_project?.frontend?.version)

instead of

if (
    configuration && 
    configuration.my_project && 
    configuration.my_project.frontend && 
    configuration.my_project.frontend.version
)

But how do I handle this if I want to do this for dynamic keys using variables?

configuration[project][app].version

would fail for { my_project: {} } as there is no frontend.

So if I want to check if version is missing for a specific app in a specific project, I’m going this way:

if (
    configuration &&
    configuration[project] &&
    configuration[project][app] &&
    !configuration[project][app].version
)

The only part I see is just !configuration[project][app]?.version, but this would also fail for { my_project: {} }

Solution

Use:

configuration?.[project]?.[app]?.version

But if you want to check specifically that version is missing (i.e. falsey) you’ll need to split your tests:

const my_app = configuration?.[project]?.[app];
if (my_app && !my_app.version) {
    ...
}

Answered By – Alnitak

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published