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.
1. To determine if a field exists in a particular substructure, use 'isfield' on that substructure instead of the top level. In the example, the value of a.b is itself a structure, and you can call 'isfield' on it. Note: If the first input argument is not a structure array, then 'isfield' returns 0 (false).
We can check if a property exists in the object by checking if property !== undefined . In this example, it would return true because the name property does exist in the developer object.
There are mainly two methods to check the existence of a key in JavaScript Object. The first one is using “in operator” and the second one is using “hasOwnProperty() method”. Method 1: Using 'in' operator: The in operator returns a boolean value if the specified property is in the object.
This will ignore attributes passed down through the prototype chain.
if(obj.hasOwnProperty('field')) { // Do something }
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) { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With