Today, I encountered a tricky situation involving the JavaScript Object.hasOwnProperty method.
I was working on a form that creates properties on an object. The issue arose when dealing with a select box that had a value selected and then reset back to its default value or left blank.
For example:
var MemberSchema = {
name: 'Name',
country: 'Country'
//etc...
}
function validateMember(member){
for(var k in MemberSchema){
if(!member.hasOwnProperty(k)){
return false;
}
}
return true
}
The problem stemmed from the form updating as soon as the select box was changed.
member.country = 'USA'
However, occasionally due to user error, the select box would be reverted back to
--Select Country--
which has an undefined value resulting in:
member.country = undefined
This caused the validateMember function to fail in recognizing a complete member object.