Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@HereComesJuju
Forked from jasonrhodes/getProperty.js
Created April 6, 2018 08:57
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 HereComesJuju/904ccd0431f2905acfd6d4e53b78ebbd to your computer and use it in GitHub Desktop.
Save HereComesJuju/904ccd0431f2905acfd6d4e53b78ebbd to your computer and use it in GitHub Desktop.
Get a nested object property by passing a dot notation string as the property name
/**
* A function to take a string written in dot notation style, and use it to
* find a nested object property inside of an object.
*
* Useful in a plugin or module that accepts a JSON array of objects, but
* you want to let the user specify where to find various bits of data
* inside of each custom object instead of forcing a standardized
* property list.
*
* @param String nested A dot notation style parameter reference (ie "urls.small")
* @param Object object (optional) The object to search
*
* @return the value of the property in question
*/
function getProperty( propertyName, object ) {
var parts = propertyName.split( "." ),
length = parts.length,
i,
property = object || this;
for ( i = 0; i < length; i++ ) {
property = property[parts[i]];
}
return property;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment