Possible Duplicate:
javascript test for existence of nested object key
I'm attempting to construct an error message for a formset
by testing if a certain object is not undefined
, and if it's not undefined
, then I end up populating it with that error message. The main problem is that I have to validate if each nested object is undefined
, which results in some pretty ugly code. Here's the example:
errorsForField: function(fieldName, formsetName, formNumber) {
if (typeof this.model.errors != 'undefined'){
var fieldError = document.createElement('span');
$(fieldError).addClass('field-error');
// THE FOLLOWING LINE THROWS ERROR.
if (formsetName && _.isUndefined(this.model.errors[formsetName][fieldName]) != true) {
$(fieldError).text(this.model.errors[formsetname][fieldName]);
} else if (typeof this.model.errors[fieldName] != "undefined"){
$(fieldError).text(this.model.errors[fieldName]);
}
this.errors[fieldName] = fieldError.outerHTML;
return fieldError.outerHTML;
}
return false;
},
I get an error stating that I cannot determine [fieldName]
of an undefined object
this.model.errors[formsetName]
. In other words, I have to first determine if this.model.errors[formsetName]
is empty and then test if [fieldname]
is undefined
.
This seems like a really cumbersome solution. Any suggestions for changing this?