Referring to @str's answer, if response
does not have a pickupLocation
property, this will result in a TypeError (Cannot read property latitude of undefined), regardless of the OR operator.
You could wrap this in a try-catch. Then you would return response.pickupLocation.latitude || fallback
in try or fallback
in a catch block.
This will not handle the defined by falsey values (imagine that response.pickupLocation.latitude
is 0
). This function will return a fallback
value, not 0
. This can be handled easily by checking typeof (typeof response.pickupLocation.latitude !== 'undefined' ? response.pickupLocation.latitude : fallback
), however we are still talking about a hardcoded object path.
The same issue is presented on the accepted answer as well.
To handle this dynamically for any object path, you have to loop over a provided object, check for hasOwnProperty
and peel off the nested properties by each iteration until you get to end of the specified path. Something like this:
const getSafe = (object, path, fallback) => {
const fragments = path.split('.')
let value
for (let i = 0; i < fragments.length; i++) {
if (!obj.hasOwnProperty(fragments[i])) {
return fallback;
}
value = object[fragments[i]];
}
return value;
}