How do I check if an object has a key in JavaScript?

JavascriptObject

Javascript Problem Overview


Which is the right thing to do?

if (myObj['key'] == undefined)

or

if (myObj['key'] == null)

or

if (myObj['key'])

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkevinView Question on Stackoverflow
Solution 1 - JavascriptForYourOwnGoodView Answer on Stackoverflow
Solution 2 - JavascripttypeoneerrorView Answer on Stackoverflow