Last active
October 15, 2020 02:13
-
-
Save lovemecomputer/0c4d8377c8f0d08096d08fbea937e664 to your computer and use it in GitHub Desktop.
search within nested properties of an object, stops searching when hitting a null property — taken from: https://medium.com/javascript-inside/safely-accessing-deeply-nested-values-in-javascript-99bf72a0855a
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
/** | |
* search within nested properties of an object, stops searching when hitting a null property | |
* e.g. for this.soundCloudAudio._track.user.avatar_url, | |
* let avatarUrl = getPropValue( ['_track', 'user', 'avatar_url'], this.soundCloudAudio ) // assigned null if property doesn't exist | |
* @param {Array} pathToProp the path to a nested prop we hope to find, each step listed as an array value (string for keys, number for indexes) | |
* @param {Object} objectToScan the object to look through for all available properties based on the path above | |
* @return {varies} returns null, or the value found at the requested property | |
*/ | |
const getPropValue = (pathToProp, objectToScan) => | |
return pathToProp.reduce( | |
(step, otherStep) => (step && step[otherStep] ? step[otherStep] : null), | |
objectToScan |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment