Check if an Object Contains all Keys in Array in Javascript

📣 Sponsor

Sometimes in Javascript we have an object which we need to conform to a specific set of keys. This is possible through type enforcement in TypeScript, but if we want to do certain things if the keys don’t exist, then we have to take a different approach.

For example, suppose we are receiving the following object from an array, where firstName, lastName, and age are all needed for an operation we want to complete. For example

let obj = { firstName: Jack, lastName: Doe, age: 123 } console.log(`${obj.firstName} ${obj.lastName} is ${obj.age}`);

If we are receiving our data in obj from an array, we could trust that those properties will be provided, but if the API ever changes we may face issues. The developers of the API may decide to remove age or any other property, or maybe rename firstName to first_name. In the best scenario, this will lead to keys becoming undefined. In the worst, it may result in an error and crash our application.

To avoid this, we can check the object has the keys we require.

How to Check if Object Contains all Keys in Array

The solution to this problem uses every(). every() is an array method which checks every element in an array, and performs a logical check on them. If all return true, then the every() method returns true.

To check if an object contains all keys in an array, we just use every() on an array of all the keys we want to check. That way we can logically check each element exists, and then do something else if it’s false, preventing us from encountering any errors:

let requiredKeys = [ 'firstName', 'lastName', 'age' ] let obj = { firstName: Jack, lastName: Doe, age: 123 } let checkAllKeys = requiredKeys.every((i) => obj.hasOwnProperty(i)); if(checkAllKeys) { console.log(`${obj.firstName} ${obj.lastName} is ${obj.age}`); } else { console.log('The API does not have all the keys required. Please check API and configuration') }

Here we create an array of our required keys - firstName, lastName, and age. We then use every() to go through each item in that array. In every(), we run a function - here, i is the the current item being looped through. If obj has the property i, then every() will return true for that specific item.

If every item returns true, then every returns true overall. Otherwise it will return false. As such, if checkAllKeys is true, we can be sure it has all the keys we need. Otherwise, we can do something else - like console log an error.

Last Updated 1651259725467

More Tips and Tricks for Javascript

Subscribe for Weekly Dev Tips

Subscribe to our weekly newsletter, to stay up to date with our latest web development and software engineering posts via email. You can opt out at any time.

Not a valid email