Skip to content

JavaScript checks if the object has key | Example code

  • by

Use JavaScript in the operator to check if the object has the key. Use myObj.hasOwnProperty('key') to check an object’s own keys and will only return true if key is available on myObj directly:

if ('key' in myObj)

And the inverse.

if (!('key' in myObj))

Note: The in operator matches all object keys, including those in the object’s prototype chain.

OR

myObj.hasOwnProperty('key')

Unless you have a specific reason to use the in operator, using myObj.hasOwnProperty('key') produces the result most code is looking for.

JavaScript checks if the object has a key

Simple example code checking name key in a given object.

<!DOCTYPE html>
<html>
<body>

  <script>
    const item = { id: '101', name: 'Goggles', price: 1499 };

    if ('name' in item){
      console.log(item)
    }
  </script>

</body>
</html> 

Output:

JavaScript checks if the object has key

Another way is to use the hasOwnProperty() method of the object:

const item = { id: '101', name: 'Goggles', price: 1499 };
var res = item.hasOwnProperty('color')

console.log(res)

Output: false

Using the in operator: You can also use the in operator to check if a key exists in an object:

const myObject = {
  key1: 'value1',
  key2: 'value2',
};

if ('key1' in myObject) {
  console.log('myObject has key1');
} else {
  console.log('myObject does not have key1');
}

Using the Object.keys method: The Object.keys method returns an array of an object’s own enumerable property names. You can use it to check if a key exists by checking if the key is included in the array of keys:

const myObject = {
  key1: 'value1',
  key2: 'value2',
};

if (Object.keys(myObject).includes('key1')) {
  console.log('myObject has key1');
} else {
  console.log('myObject does not have key1');
}

Using the Object.getOwnPropertyNames method: Similar to Object.keys, you can use the Object.getOwnPropertyNames method to get an array of an object’s own property names (including non-enumerable ones):

const myObject = {
  key1: 'value1',
  key2: 'value2',
};

if (Object.getOwnPropertyNames(myObject).includes('key1')) {
  console.log('myObject has key1');
} else {
  console.log('myObject does not have key1');
}

Each of these methods can be used to determine if a specific key exists within an object, and you can choose the one that best suits your needs.

Comment if you have any doubts or suggestions on this Js object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

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