Skip to content

Instantly share code, notes, and snippets.

@rcy
Last active December 21, 2015 05:08
Show Gist options
  • Save rcy/6254408 to your computer and use it in GitHub Desktop.
Save rcy/6254408 to your computer and use it in GitHub Desktop.
// 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