Recently Stumbled upon this nice snippet for accessing Nested property using String.
/**
* get property of object
* @param obj object
* @param path e.g user.name
*/
function getProperty(obj, path, defaultValue = '-') {
const value = path.split('.').reduce((o, p) => o && o[p], obj);
return value ? value : defaultValue;
}
and this how you use it
getProperty(object, 'passengerDetails.data.driverInfo.currentVehicle.vehicleType')
Reference
https://stackoverflow.com/a/64239231/11164153
Would be interested to learn if there is any other easier or better way.
Top comments (1)
I think you should never use naive boolean conversion for such things because JS has at least 6 falsy types which can be used as regular values. This function you showed, gives you false positive result when you try extract that kind of values:
Instead of naive boolean conversions to check if object property exists always use
.hasOwnProperty
.👍 As a possible solution for your needs (return some defaults if path is incorrect) you can use symbols: