Advertisement
Advertisement


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


Question

Which is the right thing to do?

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

or

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

or

if (myObj['key'])
2017/01/23
1
1249
1/23/2017 3:46:20 PM

Accepted Answer

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.

2018/01/24
2225
1/24/2018 5:36:03 PM

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');
2020/01/09

Source: https://stackoverflow.com/questions/455338
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]