Skip to content

Instantly share code, notes, and snippets.

@CarlinCanales
Created May 20, 2014 20:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CarlinCanales/58c4a23853fc705efd38 to your computer and use it in GitHub Desktop.
Save CarlinCanales/58c4a23853fc705efd38 to your computer and use it in GitHub Desktop.
This function will take any object/json and a property/key you want to search for. It will return the path as a string. I just created this code and will continue to update it. If you find any bugs please let me know. Right now it will return the last instance of the value you pass it. I am working on returning an array of all the paths. The las…
function getPath(object, value) {
var pathToUse = "",
path = [],
level = 0;
function traverse(o, prop) {
var keys = Object.keys(o);
for ( var i = 0, len = keys.length; i < len; i++ ) {
if ( typeof(o[keys[i]]) == "object" ) {
path[level] = ( o[keys[i]] instanceof Array ) ? keys[i] + "::Array" : keys[i];
level += 1;
traverse(o[keys[i]], prop);
}
if ( o[keys[i]] == prop || keys[i] == prop ) {
pathToUse = (path.slice(0, level).join(".") + "." + keys[i])
.replace(/::Array\.([a-zA-Z0-9])/g, "[$1]")
.replace(/\./g, "']['");
pathToUse = "['" + pathToUse + "']";
pathToUse = pathToUse.replace(/(\[.\])('\])/g, "$2$1");
}
}
level -= 1;
}
traverse(object, value);
return pathToUse;
}
// getPath(obj, value);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment