checking/assigning from object tree in node.js / javascript -
doing following risking exception 'there no bar on undefined'
var obj = o.foo.bar
the way can think of doing above safely :
var obj = (o && o.foo && o.foo.bar ) ? o.foo.bar : null;
or putting entire thing in try/catch not option in cases me.. , results in more code if want different thing happen depending on property missing.
is there concise way perform assignment safely?
** update **
tweaked @techfoobar's answer
function resolve(obj, propertypath) { if (!propertypath) return; var props = propertypath.split('.'); var o = obj; for(var in props) { o = o[props[i]]; if(!o) return false; } return o; } var res = resolve(obj, 'apiresponse.commandresponse'); if (res){ (var in res){
seems it's going get...
one way moving function can re-use in multiple scenarios regardless of depth need go:
function resolve(_root) { if(arguments.length == 1) return _root; // in case root passed var o = _root; for(var i=1; i<arguments.length; i++) { o = o[arguments[i]]; if(!o) return undefined; } return o; }
for example object var o = {x: {y:10, c:{h: 20}}};
, can use like:
resolve(o, 'x')
gives {y:10, c:{h: 20}}
resolve(o, 'x', 'c', 'h')
gives 20
whereas
resolve(o, 'x', 'c', 'boo')
gives undefined
in case, can use like:
var obj = resolve(o, 'foo', 'bar'); if(obj !== undefined) { // resolved // stuff ... }
Comments
Post a Comment