Use the Object.values Method
We can use the Object.values
method to return an array of property values of an object.
Therefore, we can use that to check if a value exists in an object.
To do this, we write:
const obj = {
a: 'test1',
b: 'test2'
};
if (Object.values(obj).indexOf('test1') > -1) {
console.log('has test1');
}
We call indexOf
on the array of property values that are returned by Object.values
.
Since 'test1'
is one of the values in obj
, the console log should run.
Use the Object.keys Method
We can also use the Object.keys
method to do the same check.
For instance, we can write:
const obj = {
a: 'test1',
b: 'test2'
};
const exists = Object.keys(obj).some((k) => {
return obj[k] === "test1";
});
console.log(exists)
We call Object.keys
to get an array of property keys in obj
.
Then we call some
with callback to return if obj[k]
is 'test1'
.
Since the value is in obj
, exists
should be true
.
Conclusion
We can use the Object.values
method to return an array of property values of an object.
Also, we can also use the Object.keys
method to do the same check.