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.
No, JavaScript objects cannot have duplicate keys. The keys must all be unique.
You can use the JavaScript in operator to check if a specified property/key exists in an object. It has a straightforward syntax and returns true if the specified property/key exists in the specified object or its prototype chain. Note: The value before the in keyword should be of type string or symbol .
You can take benefit of indexOf and lastIndexOf . if both indexes are not same, you have duplicate.
Try the JavaScript in operator.
if ('key' in myObj)
And the inverse.
if (!('key' in myObj))
Be careful! The in
operator matches all object keys, including those in the object's prototype chain.
Use myObj.hasOwnProperty('key')
to check an object's own keys and will only return true
if key
is available on myObj
directly:
myObj.hasOwnProperty('key')
Unless you have a specific reason to use the in
operator, using myObj.hasOwnProperty('key')
produces the result most code is looking for.
You should use hasOwnProperty
. For example:
myObj.hasOwnProperty('myKey');
Note: If you are using ESLint, the above may give you an error for violating the no-prototype-builtins rule, in that case the workaround is as below:
Object.prototype.hasOwnProperty.call(myObj, 'myKey');
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