Last active
August 29, 2015 14:13
-
-
Save BrynM/466f5c3b7e2be4360726 to your computer and use it in GitHub Desktop.
Deep-dive a key from a JavaScript object without a pile of typeof or a try/catch
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
// the meat of this gist - a recursive function for diving namespaces | |
function dive(obj, path) { | |
// split the path, pluck away the first one | |
var sect = (''+path).replace(/^\./, '').split('.'), | |
curr = sect.length > 0? sect.shift(): null, | |
iter; | |
// see if our current desired match exists | |
if(curr && obj && 'undefined' !== typeof obj[curr]) { | |
// last match? then return othewise recurse | |
if(sect.length === 0) { | |
return obj[curr]; | |
} else { | |
return dive(obj[curr], sect.join('.')); | |
} | |
} | |
// nothing found? undefined will get returned | |
} | |
/* SAMPLES */ | |
// the sample object we want to dive into | |
var foo = { | |
bar: { | |
baz: [1,2,3] | |
} | |
}; | |
console.log('dive foo for baz', dive(foo, 'bar.baz')); | |
// get the third installed browser plugin's name (if it exists) | |
// numeric keys should be dot notated to dive... | |
// native: window.navigator.plugins[3].name | |
console.log('dive plugin', dive(window, 'navigator.plugins.3.name')); |
Gonna put that through jsperf when I get the chance. Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See if this performs any better: