Categories
JavaScript Answers

How to Check If a Value Exists in an Object Using JavaScript?

Spread the love

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 .

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *