Oftentimes, when working on the frontend, you want to check whether an object has a key before accessing it so that you do not get an
undefined error. One way to do so is to use the
hasOwnProperty('property') which can be called from an object. This is going to return true if the object has that property and false otherwise. Next, you can check whether the property is not undefined. Let us assume that we are working with an empty object
var obj = {}; If we were to check whether the
obj has a property called
foo, we could do something like this:
obj.foo !== undefined; In this example that would return false, as there is no property called
foo. Lastly, you can use the
in operator. Based on the previous example, you could do the following:
'foo' in obj. Again, this is going to return false as the property is not set.
Reference:
https://dmitripavlutin.com/check-if-object-has-property-javascript/.