5 Ways To Check If Property Exists In Javascript Object

Welcome to a quick tutorial on how to check if a property exists in a Javascript object. In an array, we can conveniently use the includes function to check if a value exists. But in objes, things are a little different.

The common ways to check if a property exists in an object are:

  1. The easiest is to use the hasOwnProperty() function – var exist = OBJECT.hasOwnProperty("PROPERTY");
  2. Extract the keys from the object, then use the includes() function to check.
    • var keys = Object.keys(OBJECT);
    • var exist = keys.includes("PROPERTY");
  3. Use the in operator – var exist = "PROPERTY" in OBJECT;
  4. Use comparison operators – var exist = OBJECT["PROPERTY"] !== undefined;
  5. Manually loop and check the object.
    • var exist = false;
    • for (let key in OBJECT) { if (key=="PROPERTY") { exist = true; break; } }

That covers the basics, but let us walk through more 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.

 

 

REAL QUICK TUTORIAL

 

TABLE OF CONTENTS

Download & Notes Check Property Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example 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 PROPERTY EXISTS IN OBJECT

All right, let us now get into the various ways to check if a property exists in an object in Javascript.

 

1) HAS OWN PROPERTY

1-has-property.html
// (A) THE OBJECT
var theObject = { 
  Name: "John Doe", 
  Email: "john@doe.com",
  Gender: "Male"
};
 
// (B) CHECK PROPERTY EXIST
console.log(theObject.hasOwnProperty("Name")); // true
console.log(theObject.hasOwnProperty("Foo")); // false

As in the introduction above, the OBJECT.hasOwnProperty(KEY) function is one of the easiest methods to check if a property exists. But please take note – This function will only go 1 level deep and does not “dig” into nested objects.

 

2) EXTRACT KEYS & INCLUDES

2-keys.html
// (A) THE OBJECT
var theObject = { 
  Name: "John Doe", 
  Email: "john@doe.com",
  Gender: "Male"
};

// (B) GET KEYS
var keys = Object.keys(theObject);
console.log(keys); // ["Name", "Email", "Gender"]

// (C) CHECK PROPERTY EXIST
console.log(keys.includes("Email")); // true
console.log(keys.indexOf("Gender")); // 2, will return -1 if not found

This is the roundabout way to first extract all the keys of the object using Object.keys(OBJECT) first, then use either includes(KEY) or indexOf(KEY) to check if a property exists.

 

 

3) IN OPERATOR

3-in.html
// (A) THE OBJECT
var theObject = { 
  Name: "John Doe", 
  Email: "john@doe.com",
  Gender: "Male"
};

// (B) CHECK PROPERTY EXIST
console.log("Name" in theObject); // true
console.log("FOO" in theObject); // false

Yep, this should be self-explanatory. This is kind of the alternate way to do hasOwnProperty().

 

4) COMPARISON OPERATOR

4-comparison.html
// (A) THE OBJECT
var theObject = { 
  Name: "John Doe", 
  Email: "john@doe.com",
  Gender: "Male"
};

// (B) CHECK PROPERTY EXIST
console.log(theObject['Name'] !== undefined); // true
console.log(theObject['Foo'] !== undefined); // false

As you guys already know, we can use either OBJECT[KEY] or OBJECT.KEY to access the values in the object. So when OBJECT[KEY] === undefined, we can kind of assume that the key does not exist. Take extra note though, this method is not 100% accurate. We can manually define OBJECT[KEY] = undefined or OBJECT[KEY] = null.

 

 

5) MANUAL LOOP & CHECK

5-manual.html
// (A) THE OBJECT
var theObject = { 
  Name: "John Doe", 
  Email: "john@doe.com",
  Gender: "Male"
};
 
// (B) MANUAL LOOP & CHECK
var check = "Email", exist = false;
for (let key in theObject) { if (key == check) {
  exist = true;
  break;
}}
console.log(exist); // true

I know, the trolls are going to say “manual loop is so dumb and useless”. Well, let us not discount that there may still be other possible uses for it. Maybe replace the value if the key matches a search pattern, or even count the total number of instances along the way.

var count = 0;
for (let key in theObject) { if (KEY MATCHES SEARCH PATTERN) {
  theObject[key] = "FOO!";
  count++;
}}

 

6) CHECKING NESTED OBJECTS

The dreaded nested objects… Just a quick recap:

  • hasOwnProperty() will not work well, only goes 1 level deep.
  • Object.keys() will not work well, only goes 1 level deep.
  • KEY in OBJECT will also not work well, only goes 1 level deep.

So just how do we check if a property exists in a nested object? The only way is to create a recursive function to extract out all the keys.

6-nested.html
// (A) THE OBJECT
var theObject = { 
  Name: "John Doe", 
  Email: "john@doe.com",
  Gender: "Male",
  Fav: {
    Colors: ["Red", "Green", "Blue"],
    Foods: ["Pizza", "Spam", { Foo: "Bar" }]
  }
};

// (B) RECURSIVE FUNCTION TO DIG OUT ALL KEYS
var flatval = function (value) {
  let temp = [];
  if (typeof value == "object") {
    if (Array.isArray(value)) { for (let i of value) {
      if (typeof i == "object") { temp = temp.concat(flatval(i)); }
    }} else {
      temp = temp.concat(Object.keys(value));
      for (let i of temp) { if (typeof value[i] == "object") {
          temp = temp.concat(flatval(value[i]));
      }}
    }
  }
  return temp;
};
var flattened = flatval(theObject);
console.log(flattened);

// (C) FINALLY, JUST CHECK AS USUAL
console.log(flattened.includes("Foo")); // true
console.log(flattened.indexOf("Colors")); // 4

Yep. It’s painful, but it works.

 

 

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.hasOwnProperty(KEY)  Check if the object has the given key. Click Here
Object.keys(OBJECT) Return all the keys of the given object. Note, 1 level only. Click Here
ARRAY.includes(VALUE) Check 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
KEY in OBJECT Checks if the given key is in the object. Note, 1 level only. Click Here
OBJECT[KEY] !== undefined Checks if the given key is defined in the object. Click Here

 

INFOGRAPHIC CHEATSHEET

Check If Property Exists In Javascript Object (click to enlarge)

 

LINKS & REFERENCES

 

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 *