Created
September 30, 2011 14:22
-
-
Save mklabs/1253879 to your computer and use it in GitHub Desktop.
recursive deep object getter
This file contains hidden or 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
| 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