In Javascript. how can I tell if a field exists inside an object?
This will ignore attributes passed down through the prototype chain.
if(obj.hasOwnProperty('field'))
{
// Do something
}
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) {
}