Skip to content

Instantly share code, notes, and snippets.

@marioluevanos
Last active June 14, 2019 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marioluevanos/65c9f5ba26b8323404f069f6b9c83351 to your computer and use it in GitHub Desktop.
Save marioluevanos/65c9f5ba26b8323404f069f6b9c83351 to your computer and use it in GitHub Desktop.
Returns the value of nested property, or else returns undefined.
/**
* @param {Object}
* @param {String} keys - Dot notation of property access
*/
function accessProperty(object, keys) {
return keys.split('.').reduce((value, key) => value && value[key], object)
}
// Unknown if nested values will exist
const payload = {
id: '',
nested: {
title: '',
value: {
key: 'nested value'
}
}
}
// Usage
const propertyValue = accessProperty(payload, 'nested.value.key')
console.log(propertyValue)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment