Last active
April 27, 2018 16:20
-
-
Save brigand/8324917 to your computer and use it in GitHub Desktop.
This file contains 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
// 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 |
This file contains 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 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;} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sticking with the short version, we can avoid the TypeError, and get
undefined
instead, if we checkp
at each step: