Created
February 28, 2017 16:43
-
-
Save krmrn42/300b960124a45ea19360dc3c61989812 to your computer and use it in GitHub Desktop.
Find a member path by name within a JS object
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 findJsPaths(ob, name, cache) { | |
cache = cache || []; | |
var res = []; | |
for (var key in ob) { | |
var value = ob[key]; | |
if (key == name) { | |
return [key]; | |
} else if (typeof value === 'object' || value != null) { | |
if (cache.indexOf(value) == -1) { | |
cache.push(value); | |
var path = findJsPaths(ob[key], name, cache); | |
if (path != null) { | |
for (var p of path) { | |
res.push(key + '.' + p); | |
} | |
} | |
} | |
} | |
} | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment