user3142695
user3142695

Reputation: 17352

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

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: {} }

Upvotes: 0

Views: 30

Answers (2)

Alnitak
Alnitak

Reputation: 339917

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) {
    ...
}

Upvotes: 2

Seblor
Seblor

Reputation: 7146

You can use optional chaining for the brackets syntax like so:

const configuration = {}
const project = 'someProject'
const app = 'someApp'

console.log(configuration?.[project]?.[app]?.version)
configuration[project] = {}
console.log(configuration?.[project]?.[app]?.version)
configuration[project][app] = {version: '1.0.0'}
console.log(configuration?.[project]?.[app]?.version)

More details in the documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

Upvotes: 0

Related Questions