This article shows you how to check whether a key or a value exists in a given object in JavaScript.
Checking If a Key Exists
The in operator can be used to determine if a key exists in an object.
Example:
const obj = {
key1: 'value1',
key2: 'value2',
key3: 'value3'
}
if("key1" in obj) {
console.log("key1 is a key of obj")
} else {
console.log("key1 is NOT a key of obj")
}
if("key4" in obj){
console.log("key4 is a key of obj")
} else {
console.log("key4 is NOT a key of obj")
}
Output:
key1 is a key of obj
key4 is NOT a key of obj
You can also use the hasOwnProperty() method to check if a key belongs to the object itself and is not inherited from another object:
if (obj.hasOwnProperty("someKey")) {
// do something
}
Checking If a Value Exists
We can use the Object.values() method to get an array of the object’s values and then use the indexOf() or includes() method to check if a value exists in that array.
Example:
const obj = {
key1: 'value1',
key2: 'value2',
key3: 'value3'
}
// check if "value3" is in the object
if (Object.values(obj).includes('value3')) {
console.log('value3 is in the object')
} else {
console.log('value3 is not in the object')
}
// check if "value10" is in the object
if (Object.values(obj).includes('value10')) {
console.log('value10 is in the object')
} else {
console.log('value10 is not in the object')
}
Output:
value3 is in the object
value10 is not in the object
That’s it. Happy coding!