Last active
August 29, 2015 14:22
-
-
Save diegocard/e18c8c4632b1488b688a to your computer and use it in GitHub Desktop.
Find an object key deeply nested in an object (requires underscore)
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
| 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