EN
JavaScript - check if object has key
0 points
In this article, we would like to show you how to check if object has certain key in JavaScript.
Quick solutions:
xxxxxxxxxx
1
if (Object.prototype.hasOwnProperty.call(myObject, 'key')) {
2
// ...
3
}
or:
xxxxxxxxxx
1
if ('key' in myObject) {
2
// ...
3
}
Warnings:
using
myObject.hasOwnProperty()
construction may lead to mistakes by function overriding.
Incorrect code:xxxxxxxxxx
1if (myObject.hasOwnProperty('key')) {
2// ...
3}
- it is more safe to use
hasOwnProperty()
function thanin
operator.
In this example we use hasOwnProperty()
method to check if user object has age
property.
xxxxxxxxxx
1
const user = { id: 1, name: 'Tom', age: 25 };
2
3
if (Object.prototype.hasOwnProperty.call(user, 'name')) {
4
console.log('The user object contains name property.');
5
}
Note:
This solution is safer than
in
operator.
In this example we use in
operator to check if user object has age
property.
xxxxxxxxxx
1
const user = { id: 1, name: 'Tom', age: 25 };
2
3
if ('name' in user) {
4
console.log('The user object contains name property.');
5
}
Warning:
The
in
operator matches all object keys, including those in the object's prototype chain.