Skip to content

Instantly share code, notes, and snippets.

@c4urself
Created December 5, 2012 21:13
Show Gist options
  • Save c4urself/4219549 to your computer and use it in GitHub Desktop.
Save c4urself/4219549 to your computer and use it in GitHub Desktop.
Javascript querying object traversal
/**
* 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