Skip to content

Instantly share code, notes, and snippets.

@diegocard
Last active August 29, 2015 14:22
Show Gist options
  • Save diegocard/e18c8c4632b1488b688a to your computer and use it in GitHub Desktop.
Save diegocard/e18c8c4632b1488b688a to your computer and use it in GitHub Desktop.
Find an object key deeply nested in an object (requires underscore)
function keyLookup(obj, string) {
if (_.isObject(obj)) {
var path = null;
_.find(obj, function(value, key) {
if (_.isString(key) && key.includes(string)) {
path = key.toString();
return true;
} else if (_.isObject(value) && !_.isFunction(value)) {
var foundKeyValueRec = keyLookup(value, string);
// Call recursively
if (foundKeyValueRec) {
path = key + ' : ' + foundKeyValueRec;
return true;
}
}
});
return path;
}
}
// Test:
var testObj = {
someStuff: 1,
someObjectStuff: {
arr: [1, 2, 3]
},
a: {
b: {
func : function() {
return 1;
},
c: [
{
test : {
f : 1
}
},
1
]
}
}
}
keyLookup(testObj, "test") // returns "a : b : c : 0 : test"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment