Skip to content

Instantly share code, notes, and snippets.

@c0debreaker
Forked from brigand/extract-unsafe.js
Created August 26, 2014 22:31
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 c0debreaker/9a65d5e4540a4794e34b to your computer and use it in GitHub Desktop.
Save c0debreaker/9a65d5e4540a4794e34b 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 = keys.split("."), 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