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 theObj = { foo: "bar" };
    • var hasVal = Object.values(theObj).includes("bar");
  2. Manually loop through the object and check each value –
    • var hasVal = false;
    • for (let key in theObj) { if (theObj[key] == "SEARCH") { hasVal = 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.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Value In Object Useful Bits & Links
Tutorial Video The End

 

DOWNLOAD & NOTES

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

 

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.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer 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.

 

 

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 theObject = { 
  Name: "John Doe", 
  Email: "john@doe.com",
  Gender: "Male"
};
 
// (B) EXTRACT ALL VALUES
var values = Object.values(theObject);
console.log(values); // ["John Doe", "john@doe.com", "Male"]
 
// (C) CHECK USING ARRAY FUNCTIONS
console.log(values.includes("John Doe")); // true
console.log(values.indexOf("John 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 theObject = { 
  Name: "John Doe", 
  Email: "john@doe.com",
  Gender: "Male"
};

// (B) MANUALLY LOOP & SEARCH
var musthave = "John Doe";
var found = false;
for (let key in theObject) {
  if (theObject[key] == musthave) {
    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 = "John Doe";
for (let key in theObject) {
  if (theObject[key] == check) { 
    theObject[key] = "FOO";
    count++; 
  } 
}
console.log(count);

 

EXAMPLE 3) CHECK IF VALUE EXISTS IN NESTED OBJECTS

3-nested.js
// (A) THE OBJECT
var theObject = { 
  Name: "John Doe", 
  Email: "john@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 values = Object.values(theObject);
console.log(values); // ["John Doe", "john@doe.com", "Male", OBJECT]
console.log(values.includes("Pizza")); // false
*/

// (C) WE NEED A RECURSIVE FUNCTION TO DIG DEEP
var flatval = function (value) {
  var temp = [];
  if (typeof value == "object") {
    // ARRAY
    if (Array.isArray(value)) {
      for (let i of value) { temp = temp.concat(flatval(i)); }
    }
    // OBJECT
    else {
      for (let i in value) { temp = temp.concat(flatval(value[i])); }
    }
  } 
  // FLAT STRING, NUMBER, OR BOOLEAN
  else { temp.push(value); }
  return temp;
};
 
// (D) GO!
var flattened = flatval(theObject);
console.log(flattened); // ALL VALUES IN FLAT ARRAY
console.log(flattened.includes("Pizza")); // true
console.log(flattened.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.

 

 

USEFUL 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 *