ChatGPT解决这个技术问题 Extra ChatGPT

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

This question already has answers here: How do I check if an object has a specific property in JavaScript? (31 answers) Closed 8 years ago.

Which is the right thing to do?

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

or

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

or

if (myObj['key'])
You can try !!myObj.key which returns true (if in) and false (if not).
@Anh-ThiDINH be careful, this doesn't work with boolean values. const user = { name: "John", admin: false }; !!user.name will return true. But !!user.admin will return false even though the 'admin' key exists
now best would be myObj?.key
I'm vote #1700 on your duplicate question :) Well done.

D
Dinei

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.


The reason 'in' is considered not good is because it searches the whole prototype chain.
and even better - if(myObj && 'key' in myObj)
what is wrong with searching the whole prototype chain (unless you know you don't want to for some reason)?
@reconbot, in normal OO languages you often invoke methods defined in parent classes. What is wrong doing the same thing in js? Does it imply js prototype chains themselves are bad? Some people might actually use them.
could have done like this Object.keys(ObjectInWhichYouwantTocheckTheKey).includes('keyInObject') :) cheers
M
Mustafa Ehsan Alokozay

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

one problem i found with hasOwnProperty in firefox is it will return false for inherited key
@maldy: isn't that the whole point of has**Own**Property ?
ESLint rejects this as Do not access Object.prototype method 'hasOwnProperty' from target object.
@CJBrew it might be because you have the eslint flag no-prototype-builtins in which case you can still use it by doing {}.hasOwnProperty.call(object, "key")
I'm gonna leaves this here for anyone that will wonder why ESLint is complaining eslint.org/docs/rules/no-prototype-builtins