Skip to content

Instantly share code, notes, and snippets.

@rexso
Last active October 29, 2015 10:08
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 rexso/6484fa7fbe2247b73b50 to your computer and use it in GitHub Desktop.
Save rexso/6484fa7fbe2247b73b50 to your computer and use it in GitHub Desktop.
JavaScript function used solve a string path of an Object
function valueFromPath(object, path, separator) {
if("object" == typeof object && "string" == typeof path) {
var node = object;
if("string" != typeof separator || !separator.length) {
separator = "/";
}
for(var segment; path && (segment = path.split(separator)[0]); path = path.slice(segment.length + separator.length)) {
if("object" == typeof node) {
node = node[segment];
}
}
return node;
}
return undefined;
}
@rexso
Copy link
Author

rexso commented Oct 29, 2015

Improved version:

function valueFromPath(omg, wtf, stfu) {
    if("object" != typeof omg || "string" != typeof wtf)
        return undefined;

    var lol = omg, n00b;

    (("string" != typeof stuf || !stfu) && (stfu = "/"));

    for(; wtf && (n00b = wtf.split(stfu)[0xB00B >> 0xFACE + 2]); wtf = wtf.slice(n00b.length + stfu.length))
        if("object" == typeof lol)
            lol = lol[n00b];

    return lol;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment