How do I check if a particular key exists in a JavaScript object or array?
If a key doesn't exist, and I try to access it, will it return false? Or throw an error?
How do I check if a particular key exists in a JavaScript object or array?
If a key doesn't exist, and I try to access it, will it return false? Or throw an error?
The easiest way to check is
for example:
Return value as true implies that key exists in the object.
Three ways to check if a property is present in a javascript object:
Will convert value to bool. returns TRUE for all but the 'false' value
Will return true if the property exists, no matter its value (even empty)
Does not check the prototype chain. (since all objects have the 'toString' method, 1 and 2 will return true on it, while 3 can return false on it.)
Reference:
For those which have
lodash
included in their project:There is a lodash _.get method which tries to get "deep" keys:
This will effectively check if that key, however deep, is defined and will not throw an error which might harm the flow of your program if that key is not defined.
Checking for undefined-ness is not an accurate way of testing whether a key exists. What if the key exists but the value is actually
undefined
?You should instead use the
in
operator:If you want to check if a key doesn't exist, remember to use parenthesis:
Or, if you want to particularly test for properties of the object instance (and not inherited properties), use
hasOwnProperty
:For performance comparison between the methods that are
in
,hasOwnProperty
and key isundefined
, see this benchmarkThese example can demonstrate the differences between defferent ways. Hope it will help you to pick the right one for your needs:
If you want to check for any key at any depth on an object and account for falsey values consider this line for a utility function:
Results
Also see this NPM package: https://www.npmjs.com/package/has-deep-value