In Javascript. how can I tell if a field exists inside an object?
JavascriptJavascript Problem Overview
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.
Javascript Solutions
Solution 1 - Javascript
This will ignore attributes passed down through the prototype chain.
if(obj.hasOwnProperty('field'))
{
// Do something
}
Solution 2 - Javascript
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) {
}
Solution 3 - Javascript
In addition to the above, you can use following way:
if(obj.myProperty !== undefined) {
}
Solution 4 - Javascript
There is has method in lodash library for this. It can even check for nested fields.
_.has(object, 'a');
_.has(object, 'a.b');