In javascript, test for property deeply nested in object graph? -
i've got collection of disparate, complex json objects couchdb database. each contains many levels of nested properties--for example,
tps_report.personnel_info.productivity.units_sold = 8 i want iterate through these objects , stuff them: instance,
// writes units sold each tps report: (i in tpsreports) { if (tpsreports[i].personnel_info.productivity.units_sold < 10) { fireemployee(); } } the problem many tps reports don't have these properties set. if try this, i'll error first time loop gets report without "personnel_info" property , tries find "productivity" property of "undefined." i'd rather happen conditional skips , continues.
i see 2 ways around this, both of seem ugly me
- test each property separately nested conditionals
- enclose line in try/catch block catch error , ignore it
what i'd prefer php's isset() function, won't throw error regardless of feed it--it'll tell whether particular variable you're looking exists or not. so, like
// writes units sold each tps report: (i in tpsreports) { if (isset(tpsreports[i].personnel_info.productivity.units_sold)){ if (tpsreports[i].personnel_info.productivity.units_sold < 10) { fireemployee(); } } } any thoughts?
function isset(obj, propstr) { var parts = propstr.split("."); var cur = obj; (var i=0; i<parts.length; i++) { if (!cur[parts[i]]) return false; cur = cur[parts[i]]; } return true; } note second parameter string, exception doesn't thrown when accessing property on nonexistent property.
Comments
Post a Comment