EN
JavaScript - check if key exists in object
0 points
In this article, we would like to show you how to check if key exists in object working with JavaScript.
Quick solution:
xxxxxxxxxx
1
var object = { keyName: 'A'};
2
3
console.log('keyName' in object); // true
In this example, we use for...in
statement to check if a key exists in the object. This way true
value is returned even when the key value is undefined
.
xxxxxxxxxx
1
var object = { keyName1: 'A', keyName2: undefined };
2
3
console.log('keyName1' in object); // true
4
console.log('keyName2' in object); // true (key exists but value is undefined)
5
6
console.log('keyName3' in object); // false
You can also use hasOwnProperty()
method to achieve the same result as above.
xxxxxxxxxx
1
var object = { keyName1: 'A', keyName2: undefined };
2
3
console.log(object.hasOwnProperty('keyName1')); // true
4
console.log(object.hasOwnProperty('keyName2')); // true
5
6
console.log(object.hasOwnProperty('keyName3')); // false