DZone
Web Dev Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Web Dev Zone > Check if an Object Contains All Keys in an Array in JavaScript

Check if an Object Contains All Keys in an Array in JavaScript

Let's take a look at how to make sure objects conform to specific arrays of keys.

Johnny Simpson user avatar by
Johnny Simpson
CORE ·
May. 10, 22 · Web Dev Zone · Code Snippet
Like (3)
Save
Tweet
2.91K Views

Join the DZone community and get the full member experience.

Join For Free

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 we may face issues if the API ever changes. 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 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.

Data structure JavaScript Object (computer science)

Published at DZone with permission of Johnny Simpson, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Auth0 (Okta) vs. Cognito
  • Sprint Goals: How to Write, Manage, and Achieve
  • An Overview of DTrace and strace
  • Everything You Need to Know About Web Pentesting: A Complete Guide

Comments

Web Dev Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo