0

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

2 Answers 2

2

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) {
    ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Oh. Didn't know, that I can put an .in between... And the second thing is exactlyy, what I need. Thanks.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.