Created
December 5, 2012 21:13
-
-
Save c4urself/4219549 to your computer and use it in GitHub Desktop.
Javascript querying object traversal
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
/** | |
* Returns a value or array of values by traversing the `object` using `path` | |
* | |
* @param object {Object} | |
* @param path {String} | |
* @returns value {String, Array} | |
* | |
* traverseObject({a: {b: [{c: {d: 'gotcha!'}}, {c: {d: 'yes!'}}]}}, 'a__b____c__d'); | |
* --> ['gotcha!', 'yes!'] | |
* traverseObject({a: {b: [{c: 'gotcha!'}, {c: 'yes!'}]}}, 'a__b____c'); | |
* --> ['gotcha!', 'yes!'] | |
* traverseObject({a: {b: {c: 'gotcha!'}}}, 'a__b__c'); | |
* --> 'gotcha! | |
* traverseObject({a: {b: [{c: 'gotcha!'}]}}, 'a__b__0__c'); | |
* --> 'gotcha! | |
*/ | |
function traverseObject(object, path) { | |
var keys = path.split('__'), | |
value = object, | |
m; | |
_.each(keys, function (key) { | |
if (m) { | |
value = _.pluck(value, key); | |
m = false; | |
if (_.isObject(value[0])) { | |
m = true; | |
} | |
} else if (key === '') { | |
m = true; | |
} else { | |
value = value[key]; | |
} | |
}); | |
return value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment