Created
November 7, 2014 21:07
-
-
Save cworsley4/7e71037a8f6e850d31dd to your computer and use it in GitHub Desktop.
Deep Pluck for Object Properties
This file contains hidden or 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
/** | |
* Deep Pluck a value from an object by string. | |
* Give the method a dot delemited string to a property of the given | |
* object. It will recurse over it, until it hits the target property | |
* or, if it doesn't exist, it will return an empty string. | |
* | |
* @plug Special thanks to user 'clocklear' for his help with this Deep Pluck | |
* | |
* | |
* @param {object} object [Target option retrieve property from] | |
* @param {string} property [Property path] | |
* @param {string} objectName [Name of the targetObject if its part of the | |
* property path] | |
* @return {mixed} | |
*/ | |
function pluck (object, property, objectName) { | |
var props; | |
if (typeof property !== 'string' && typeof object !== 'object') return; | |
var keys = Object.keys(object); | |
if (property.indexOf('.') > -1) { | |
props = property.split('.'); | |
} else { | |
props = property; | |
} | |
// If objectName isn't given, assume the first value in the property | |
// string, is the name of the given object | |
if (props[0] === objectName) { | |
props.splice(0, 1); | |
} else { | |
var propString = props; | |
props = []; | |
props.push(propString); | |
} | |
if (keys.indexOf(props[0]) > -1) { | |
if (props.length > 1) { | |
return pluck( | |
object[props[0]], | |
props.splice(1, props.length).join('.'), | |
objectName | |
); | |
} else { // Base case | |
return object[props[0]]; | |
} | |
} else { | |
return ''; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment