Last active
June 14, 2019 18:44
-
-
Save marioluevanos/65c9f5ba26b8323404f069f6b9c83351 to your computer and use it in GitHub Desktop.
Returns the value of nested property, or else returns undefined.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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