How to Check if Value Exists in an Object in JavaScript
How can we check if a value exists in an object in JavaScript?
Suppose we have an object obj
.
const obj = {
id: 0,
name: "Bob"
};
We want to check if the object has a field with a certain value.
Check for object value using Object.values()
We can check if a value exists in an object using Object.values()
.
We can use includes()
to check for the value.
let exists = Object.values(obj).includes("Bob"); // true
let exists = Object.values(obj).includes("Jim"); // false
Or, we can use indexOf()
.
let exists = Object.values(obj).indexOf('Bob') > -1; // true
let exists = Object.values(obj).indexOf('Jim') > -1; // false
Check for object value using keys
Similarly, we can loop over the keys to find the value we’re looking for.
There are tons of ways to approach this.
const doesExist = (obj, value) => {
for (let key in obj) {
if (obj[key] === value) {
return true;
}
}
return false
}
let exists = doesExist(obj, "Bob");
We can also use Object.keys()
and some()
.
let exists = Object.keys(obj).some(key => obj[key] === "Bob");