And of course I want to do this code-wise. It\'s not that there isn\'t alternative to this problem I\'m facing, just curious.
In addition to the above, you can use following way:
if(obj.myProperty !== undefined) {
}
UPDATE: use the hasOwnProperty
method as Gary Chambers suggests. The solution below will work, but it's considered best practice to use hasOwnProperty
.
if ('field' in obj) {
}
This will ignore attributes passed down through the prototype chain.
if(obj.hasOwnProperty('field'))
{
// Do something
}
After much frustration trying to test a field name which is passed via a variable, I came up with this:
`function isset(fName){
try{
document.getElementById(fName).value=document.getElementById(fName).value;
return true;
}catch(err){
return false;
}
}
`
The function uses the try/catch function of javascript - if it can't set the field value it will trigger an error which is caught and passed back as false, otherwise true is returned.
There is has method in lodash library for this. It can even check for nested fields.
_.has(object, 'a');
_.has(object, 'a.b');