Skip to content

Instantly share code, notes, and snippets.

@mklabs
Created September 30, 2011 14:22
Show Gist options
  • Select an option

  • Save mklabs/1253879 to your computer and use it in GitHub Desktop.

Select an option

Save mklabs/1253879 to your computer and use it in GitHub Desktop.
recursive deep object getter
var assert = require('assert');
var o = {a: {b: 'c'}, d: {e: {f: 'GG'}}};
assert.equal(get(o, 'a'), o.a);
assert.equal(get(o, 'd'), o.d);
assert.equal(get(o, 'd.e'), o.d.e);
assert.equal(get(o, 'd.e.f'), 'GG');
assert.equal(get(o, 'foobar'), undefined);
assert.equal(get(o, 'foobar.is.not'), undefined);
assert.equal(get(o, 'foobar.is.not.there'), undefined);
function get(source, key, memo) {
memo = memo || '';
var parts = key.split('.').reverse(),
last = parts.length === 1,
thing = source[parts[parts.length - 1]] || source[parts[0]] || source[memo.split('.')[0]];
parts.pop();
if(last) {
// prevent deep traversal when we're on the last part of the key
return thing;
}
if(thing && typeof thing === 'object' ) {
return get(thing, parts.join('.'), key);
}
return thing;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment