Javascript

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

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...

Written by Luci · 50 sec read >

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.

Written by Luci
I am a multidisciplinary designer and developer with a main focus on Digital Design and Branding, located in Cluj Napoca, Romania. Profile
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x