Consider the following company
object:
var employee = {
empID: 45435,
salary: 44000,
title: "Janitor",
firstName: "Richard",
lastName: "Stallman"
}
var department = {
name: "Maintenance",
building: "H",
room: 404,
departmentLead: employee
}
var company = {
name: "Bluth's Original Frozen Banana Stand",
revenue: 'always',
maintenanceDept: department
}
If I wanted to access the title
property of the employee
object, I could reference it with:
var title = company.maintenanceDept.departmentLead.title;
However, if departmentLead
is undefined
, a TypeError
will be thrown. So, I must write a test before accessing title
:
if(company &&
company.maintenanceDept &&
company.maintenanceDept.departmentLead &&
company.maintenanceDept.departmentLead.title){ ... }
Is this the best way of doing this? Obviously, this example is contrived because I defined company
before using it, so I know title
exists. The same cannot be said for a company
object returned from an AJAX call. A solution I've been using has been:
// Edit: I've been informed adding properties to Object.prototype is not a smart thing to do...so don't do this
Object.prototype.propertyWithPath = function (path) {
var keys = path.split('.');
var parent = this;
var child;
for (var i = 0; i < keys.length; i++) {
child = keys[i];
if (parent[child] === undefined) {
return undefined;
}
parent = parent[child];
}
return parent;
};
Besides the performance hit, are there any downsides to using this method vs the alternative?