Skip to content

Instantly share code, notes, and snippets.

@brigand
Last active April 27, 2018 16:20
Show Gist options
  • Save brigand/8324917 to your computer and use it in GitHub Desktop.
Save brigand/8324917 to your computer and use it in GitHub Desktop.
// simpler, faster, version that will throw a TypeError if the path is invalid
// by yorick
function extract(obj, key){
return key.split('.').reduce(function(p, c) {return p[c]}, obj)
}
extract
// for example:
var o = {
b: ["a", "b", "c"],
d: {
e: {
q: 1
}
}
}
extract(o, "b.2") // => "c"
extract(o, "d.e.q") // => 1
extract(o, "b.not.here") // throws TypeError
function extract(obj, keys, alternative){
// for empty or undefined paths, just assume root
if (!keys) {
return obj;
}
var parts = typeof keys === "string" ? keys.split(".") : keys;
var o = obj;
for (var i=0; i < parts.length; i++) {
var part = parts[i];
if (typeof o !== "object") {
// this is the last key, so we've found the value
return alternative;
}
o = o[part];
}
if (typeof o === "undefined") {
return alternative;
}
return o;
}
// for example:
var o = {
b: ["a", "b", "c"],
d: {
e: {
q: 1
}
}
}
extract(o, "b.2") // => "c"
extract(o, "d.e.q", 0) // => 1
extract(o, "d.e.not.here", 0) // => 0
extract(o, "b.not.here") // => undefined
// minified (esmangle)
function extract(d,e,f){if(!e)return d;var c=e.split('.'),a=d;for(var b=0;b<c.length;b++){var g=c[b];if((typeof a)[0]!='o')return f;a=a[g];}return a===void 0?f:a;}
@joeytwiddle
Copy link

joeytwiddle commented Apr 27, 2018

Sticking with the short version, we can avoid the TypeError, and get undefined instead, if we check p at each step:

function extract(obj, key){
    return key.split('.').reduce(function(p, c) {return p ? p[c] : undefined}, obj)
}

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