getprop
Get a property from nested object, the easy way.
Antiquated way:
var value = 'default value';
if (
obj &&
obj.qux &&
obj.qux.zee &&
obj.qux.zee.peep &&
obj.qux.zee.peep[2] &&
obj.qux.zee.peep[2].__data) {
value = obj.qux.zee.peep[2].__data;
}
with getProp:
var value = getProp(obj, ['qux', 'zee', 'peep', 2, '__data']);
Install
npm install get-prop
bower install getprop
Usage
var getProp = require('get-prop');
var obj = {
foo: 'bar',
qux: {
zee: {
boop: 4,
peep: [55,'zonk', {
__data: 'pow'
}],
},
'key.with.dots': 'hello',
'"key.with.quotes"': {
greet: 'hi'
},
$el: 'element'
},
'foo.bar': 'noob',
qax: null
};
getProp(obj, ['foo'])
getProp(obj, ['deedee'])
getProp(obj, ['deedee'], "I'm default value")
getProp(obj, ['qux', 'zee', 'boop'])
getProp(obj, ['qux', 'zee', 'peep', 0])
getProp(obj, ['qux', 'zee', 'peep', 1])
getProp(obj, ['qux', 'key.with.dots'])
getProp(obj, ['qux', '"key.with.quotes"', 'greet'])
getProp(obj, ['qux', 'zee', 'peep', 2])
getProp(obj, ['qux', 'zee', 'peep', 2, '__data'])
getProp(obj, ['qux', '$el'])
getProp(obj, ['foo.bar'])
getProp(obj, ['qux', 'qux'])
getProp(obj, 'foo')
getProp(obj, 'deedee')
getProp(obj, 'deedee', "I'm default value")
getProp(obj, 'qux.zee.boop')
getProp(obj, 'qux.zee.peep.0')
getProp(obj, 'qux.zee.peep.1')
getProp(obj, 'qux.zee.peep[1]')
getProp(obj, 'qux[key.with.dots]')
getProp(obj, 'qux["key.with.quotes"].greet')
getProp(obj, 'qux.zee.peep.2')
getProp(obj, 'qux.zee.peep.2.__data')
getProp(obj, 'qux.$el')
getProp(obj, '[foo.bar]')
getProp(obj, 'qux.qux')
Partially applied:
var objProp = getProp(obj);
objProp(['foo']) // 'bar'
objProp('[foo.bar']) // 'noob'
objProp(['qux']) // 'noob'
objProp(['yo'], 'wut') // 'wut'
For a boolean version of this, check out the module hasprop.
License
MIT