Tyler Turden
Tyler Turden

Reputation: 151

Javascript: Is there a clean way to access object properties depending on whether a variable's value exists?

Context:

This is more of styling question in hopes of writing cleaner code.

Problem:

As shown in the code below, depending on whether certain variables hold a value or not, the code uses the variable to access deeper into the object. I have a feeling that there must be a cleaner way to go about this so I'm curious to get some inputs on this. Any insights are greatly appreciated. Thank you!

Code:

if (!stageKey) {
    return dataRefreshSpec?.data
}

if (!datasetType) {
    return dataRefreshSpec?.data[stageKey]
}

return dataRefreshSpec?.data[stageKey][datasetType]

Upvotes: 0

Views: 31

Answers (1)

user12407908
user12407908

Reputation:

I might first test for the existence of the full path, and then access it. If it isn't there, then you know you can only go so far as the stageKey if it exists, otherwise just the .data.

if (stageKey && datasetType) {
    return dataRefreshSpec?.data[stageKey][datasetType]
}

return stageKey ? dataRefreshSpec?.data[stageKey] : dataRefreshSpec?.data

Or like this, if I got the new syntax right:

return dataRefreshSpec?.data?.[stageKey]?.[datasetType] ??
       dataRefreshSpec?.data?.[stageKey] ??
       dataRefreshSpec?.data

Or there's this old standby, which will probably work, depending on your requirements:

return (((dataRefreshSpec || {}).data || {})[stageKey] || {})[datasetType]

These last two are technically a little different, since they don't test the value of they key itself, but rather its result when applying its value to the objects.

Upvotes: 1

Related Questions