2 Ways To Check If Value Exists In Javascript Object

Welcome to a quick tutorial on how to check if a value exists in an object in Javascript. So you have probably tried to do a includes("VALUE") to check if an object contains a certain value. But as it turns out, objects don’t have that very convenient function.

The common ways to check if a value exists in a Javascript object is to:

  1. Extract all the values from the object into an array, then use the includes() function to check.
    • var obj = { foo: "bar" };
    • var has = Object.values(obj).includes("bar");
  2. Manually loop through the object and check each value –
    • var has = false;
    • for (let key in obj) { if (obj[key] == "SEARCH") { has = true; break; }}

P.S. If you are looking to check if a property exists – Read this guide instead.

That covers the basics, but let us walk through a few detailed examples in this guide, read on!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TLDR – QUICK SLIDES

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

First, here is the download link to the example source code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

CHECK IF VALUE EXISTS IN OBJECT

All right, let us now go into the various example on how to check if a certain exists in an object.

 

EXAMPLE 1) EXTRACT ALL VALUES INTO AN ARRAY

1-values.js
// (A) THE OBJECT
var obj = {
  Name: "Jon Doe",
  Email: "jon@doe.com",
  Gender: "Male"
};
 
// (B) EXTRACT ALL VALUES INTO ARRAY
var val = Object.values(obj);
console.log(val); // ["Jon Doe", "jon@doe.com", "Male"]
 
// (C) CHECK USING ARRAY FUNCTIONS
console.log(val.includes("Jon Doe")); // true
console.log(val.indexOf("Jon Doe")); // 0, will be -1 if not found

This is pretty much just an “expanded version” of the simple snippet in the introduction. The key points are:

  • Object.values(OBJECT) will return all the values of the object in an array.
  • Once we have an array of values, we can easily use either ARRAY.includes(VALUE) or ARRAY.indexOf(VALUE) to check.

That’s all.

 

 

EXAMPLE 2) MANUAL LOOP TO CHECK FOR VALUE

2-manual.js
// (A) THE OBJECT
var obj = {
  Name: "Jon Doe",
  Email: "jon@doe.com",
  Gender: "Male"
};

// (B) MANUALLY LOOP & SEARCH
var check = "Jon Doe";
var found = false;
for (let key in obj) { if (obj[key] == check) {
  found = true;
  break;
}}
console.log(found); // true

This is the alternative way where we manually loop through the object to find the given value, and it’s not wrong… Before the dumb trolls start to spit “this is stupid and useless”, it still has its own possible uses. For example, we can count the total number of occurrences or change all the values at once.

var count = 0;
var check = "Jon Doe";
for (let key in obj) { if (obj[key] == check) { 
  obj[key] = "FOO DOE";
  count++; 
}}
console.log(count);

 

EXAMPLE 3) CHECK IF VALUE EXISTS IN NESTED OBJECTS

3-nested.js
// (A) THE OBJECT
var obj = {
  Name: "Jon Doe",
  Email: "jon@doe.com",
  Gender: "Male",
  Numbers: [12, 34],
  Fav: {
    Colors: ["Red", "Green", "Blue"],
    Foods: ["Pizza", "Spam"]
  }
};

/*
// (B) THIS WILL NOT WORK!
// values() WILL ONLY RETURN FIRST LEVEL
var val = Object.values(obj);
console.log(val); // ["Jon Doe", "jon@doe.com", "Male", OBJECT]
console.log(val.includes("Pizza")); // false
*/

// (C) WE NEED A RECURSIVE FUNCTION TO DIG DEEP
var flatten = value => {
  // (C1) COLLECT ALL VALUES IN TEMP
  let temp = [];
 
  // (C2) ARRAY OR OBJECT
  if (typeof value == "object") {
    if (Array.isArray(value)) {
      for (let i of value) { temp = temp.concat(flatten(i)); }
    } else {
      for (let i in value) { temp = temp.concat(flatten(value[i])); }
    }
  }
 
  // (C3) FLAT STRING, NUMBER, OR BOOLEAN
  else { temp.push(value); }
 
  // (C4) FLATTENED VALUE
  return temp;
};
 
// (D) GO!
var flat = flatten(obj);
console.log(flat); // all values in flat array
console.log(flat.includes("Pizza")); // true
console.log(flat.indexOf("Pizza")); // 8

Now, the above methods are probably “the easy way out”, but they have a critical flaw – It only goes in 1 level deep. Values that are nested deep inside will not be found.

So here it is, the accursed solution using the confusing recursion… Basically, dig into every array and object to return a “flat array of values” – Then, Captain Obvious, use includes() or indexOf to check.

 

 

EXTRA BITS & LINKS

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

 

SUMMARY

Function/Statement Description Reference Link
Object.values(OBJECT) Get all the values of the object. Note – First level only. Click Here
ARRAY.includes(VALUE) Checks if the given value exists in the array. Click Here
ARRAY.indexOf(VALUE) Returns the index of the given value, -1 if not found. Click Here

 

LINKS & REFERENCES

 

TUTORIAL VIDEO

 

INFOGRAPHIC CHEAT SHEET

How To Check If Value Exists In Object (Click to enlarge)

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

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