Skip to content

Instantly share code, notes, and snippets.

@BrynM
Last active August 29, 2015 14:13
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 BrynM/466f5c3b7e2be4360726 to your computer and use it in GitHub Desktop.
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
// 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'));
@dudrenov
Copy link

See if this performs any better:

function bork(obj, path) {
  var keys = (''+path).replace(/^\./, '').split(/\./);
  if (keys.length == 0) {
    return;
  }

  var result = obj;
  for (var i = 0, l = keys.length; i < l; ++i) {
    result = result[keys[i]];
    if (!result) {
      return;
    }
  }

  return result;
}

@BrynM
Copy link
Author

BrynM commented Jan 22, 2015

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