Last active
December 21, 2015 05:08
-
-
Save rcy/6254408 to your computer and use it in GitHub Desktop.
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
// key is a string of possibly dotted accessors | |
function prop(obj, key) { | |
var keys = key.split('.'); | |
for (var i in keys) { | |
if (!obj) break; | |
obj = obj[keys[i]]; | |
} | |
return obj; | |
} | |
// test code | |
var assert = require('assert'); | |
obj = { | |
foo: { | |
bar: 23, | |
baz: 42 | |
}, | |
fred: 99, | |
a: { b: { c: { d: "deeep" } } } | |
} | |
assert.equal(prop(obj, 'foo.bar'), 23) | |
assert.equal(prop(obj, 'foo.baz'), 42) | |
assert.equal(prop(obj, 'foo.quux'), undefined) | |
assert.deepEqual(prop(obj, 'foo'), {"bar": 23, "baz": 42}) | |
assert.equal(prop(obj, 'fred'), 99) | |
assert.equal(prop(obj, 'nothing'), undefined) | |
assert.equal(prop(obj, 'a.b.c.d'), "deeep") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment