[SOLVED] Check if key exists in object in JS [3 Methods]

3 Methods to check if key exists in an object in Javascript

The three typical ways to check if key exists in object in Javascript are using:

1. in operator

Advertisement
"[key]" in [object]

2. hasOwnProperty() method

[object].hasOwnProperty("[key]")

3. undefined data type

[object].[key] !== undefined

It would be best to understand how each method works before applying it, as shown in section 3 of this tutorial.

Let's get started.

 

Method-1: Using the in operator

The most recommended way for to check if key exists in object is to use the in operator. The operator checks for a property in an object and returns a boolean.

key in object

The key can be a string or a symbol, whereas the object can be a literal or an array.

Advertisement

Object literal

const customObject = { name: "Lorem", usesUbuntu: true }

name and usesUbuntu are keys (also referred to as properties), while Lorem and true are values.

Array

An array is a special type of object which stores indexed values. The indices, which start counting from zero (), are the keys.

const simpleArray = [ "Lorem", "Ipsum", "Doe", "Adi" ]

For example, the index of Lorem, Ipsum, Doe, and Adi are , 1, 2, and 3, respectively.

Apart from checking if key exists in an object, the in operator helps to loop through an enumerable. For example, we can loop through the array, console-logging its keys and the corresponding values.

Advertisement
for (let i in simpleArray) console.log("key => ", i, ", value => ", simpleArray[i])

 

Method-2: Using hasOwnProperty() method

JavaScript has built-in methods to check if key exists in object. For example, the hasOwnProperty() method confirms whether the given property (is not inherited from another object but) belongs to the specified object.

object.hasOwnProperty(key)

The key is (a string) surrounded by quotation marks.

 

Method-3: Using the undefined data type

undefined is one of the 7 JavaScript data types: string, number, object, boolean, symbol, null, and undefined. It is a data type denoting the usage of a variable with no value.

Although you can use undefined to check for the existence of a key in an object, using it could lead to an unintended output. Take a look at this code and try to guess why nothing gets printed on the console output.

const person = { name: undefined }
if (person.name) console.log("Name key exists")

Here, we check if the name property with the undefined value exists in the person object. Nothing gets printed on the console output because assigning an object's property a value of undefined renders the property falsy, which is equivalent to empty, or false in the Boolean logic.

Nevertheless, you can still use undefined (in certain situations) to check for the existence of a key in an object, as shown below.

Advertisement

 

Lab setup to explore check if key exists in object

Open the terminal and make the project directory, and cd into it. I am creating one called GoLinuxCloud.

Next, create three files named in.js, hasOwnProperty.js, and undefined.js.

mkdir GoLinuxCloud
cd GoLinuxCloud
touch in.js hasownProperty.js undefined.js

[SOLVED] Check if key exists in object in JS [3 Methods]

We will implement check if key exists in object using the

  • in operator inside the in.js file,
  • hasOwnProperty() method inside the hasownProperty.js file, and
  • undefined data type inside the undefined.js file.

Now that we have a setup to explore check if key exists in object, let's dive into practical examples.

 

Practical examples of check if key exists in object

This section walks you through the practical implementation of check if key exists in object using various object structures.

 

Example~1: Check if key exists in object using the in operator

Assume we want to check if employees have stored their website URLs and phone numbers with the respective departments.

Advertisement

Here is a sample of the data.

const employees = {

    employee1: {
        id: 1,
        name: 'Leanne Graham',
        username: 'Bret',
        email: 'Sincere@april.biz',
        address: {
          street: 'Kulas Light',
          suite: 'Apt. 556',
          city: 'Gwenborough',
          zipcode: '92998-3874',
        },
        website: 'hildegard.org',
        company: {
          name: 'Romaguera-Crona',
          catchPhrase: 'Multi-layered client-server neural-net',
          bs: 'harness real-time e-markets'
        }
    },

    employee2:   {
        id: 2,
        name: 'Ervin Howell',
        username: 'Antonette',
        email: 'Shanna@melissa.tv',
        address: {
          street: 'Victor Plains',
          suite: 'Suite 879',
          city: 'Wisokyburgh',
          zipcode: '90566-7771',
        },
        phone: '010-692-6593 x09125',
        company: {
          name: 'Deckow-Crist',
          catchPhrase: 'Proactive didactic contingency',
          bs: 'synergize scalable supply-chains'
        }
    }

}

We check whether we have stored employee1's phone number, employee1's website URL, and employee2's website URL.

Input

// Check~1: Do we have employee1's phone number?
const employee1HasPhone = "phone" in employees.employee1
// Check~2: Do we have employee1's website URL?
const employee1HasWebsite = "website" in employees.employee1
// Check~3: Do we have employee2's website URL?
const employee2HasWebsite = "website" in employees.employee2

console.log(employee1HasPhone, employee1HasWebsite, employee2HasWebsite)

Output

false true false

We lack (false) employee1's phone, have (true) employee1's website URL, and lack (false) employee2's website URL.

Javascript check if key exists in object

 

Example~2: Check if key exists in object using the hasOwnProperty() method

Assume we are a school. We want to check if we have stored a class of details of the learners. Currently, we have the following details.

Advertisement
const learners = {
    names: ["John", "Doe", "Sam", "Smith", "Lorem", "Ipsum"],
    grades: ["C", "A", "A", "B", "A", "C"],
    marks: [56, 93, 97, 71, 86, 63],
}

Before proceeding, we check whether we have stored the marks and ages.

Input

const hasGrades = learners.hasOwnProperty('marks')
const hasAges = learners.hasOwnProperty('ages')

hasGrades && hasAges ? console.log("Proceed to check if key exists in object") : console.log("You are missing some details")

Output

You are missing some details

[SOLVED] Check if key exists in object in JS [3 Methods]

The system tells us You are missing some details because the learners object lacks the ages key.

 

Example~3: Check if key exists in object using the undefined object

Assume we are compiling a long list of top football leagues worldwide. After storing details of some leagues, we halt to check if we have stored the details of specific leagues, so we don't store the details again.

const leagues = {
    laliga: {
        clubs: ["Real Madrid", "Barcelona", "Atletico Madrid", "Sevilla", "Valencia"],
        location: "Spain"
    },
    epl: {
        clubs: ["Manchester City", "Arsenal", "Manchester United", "Chelsea", "Tottenham HotSpurs"],
        location: "England"
    },
    serieA: {
        clubs: ["Napoli", "Juventus", "AC Milan", "AS Roma", "Internazionale Milano"],
        location: "Italy"
    }
}

For example, let's check whether we have laliga and bundesliga.

Advertisement

Input

const haslaliga = leagues.laliga !== undefined
const hasBundesliga = leagues.bundesliga !== undefined

const keyExists = (key) => key ? console.log("League stored") : console.log("League missing!")

keyExists(haslaliga)
keyExists(hasBundesliga)

We attach the keys to the leagues object and check if the result is truthy by negating the comparison operator. We then console-log League stored if the outcome is truthy. Otherwise, we console-log League missing.

Output

League stored
League missing!

[SOLVED] Check if key exists in object in JS [3 Methods]

Sure, laliga exists as a key to the leagues object, whereas bundesliga is not yet stored.

 

Conclusion

Although you can take multiple routes to check if key exists in object, the most familiar ways are using the in operator, hasOwnProperty(), and undefineddata type.

 

Further Reading

Checking if a key exists in a JavaScript object?

 

Related Keywords: check if key exists in object javascript, check if key in dictionary javascript, js check if key exists, javascript check if key exists, check if key exists in object js, javascript check if key exists in object, javascript check if key in array

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X