[Solved-5 Solutions] Check does an object has property in JavaScript - javascript tutorial
Problem:
How to check if an object has a property in JavaScript ?
Solution 1:
The hasOwnProperty() method returns a boolean whether the object has the specified property as its own property to be indicated.
Solution 2:
You can use this solution:
Solution 3:
Use Underscore.js
_.has(x, 'key');
Which calls Object.prototype.hasOwnProperty, but- It is shorter to type
- Uses "a safe reference to
hasOwnProperty
" (i.e. it works even if hasOwnProperty is overwritten).
Solution 4:
A common alternative is to ensure that undefined
is actually undefined, e.g. by putting the code into a function which accepts an additional parameter, called undefined, that isn’t passed a value.