Check if object contains all keys in JavaScript array


We are required to write a function containsAll() that takes in two arguments, first an object and second an array of strings. It returns a boolean based on the fact whether or not the object contains all the properties that are mentioned as strings in the array.

So, let’s write the code for this. We will iterate over the array, checking for the existence of each element in the object, if we found a string that’s not a key of object, we exit and return false, otherwise we return true.

Here is the code for doing the same −

Example

const obj = {
   'name': 'Ashish Kumar','dob': '12/07/1991','gen': 'M','isEmployed': true,'jobType': 'full-time'
};
const obj2 = {
   'name': 'Ashish Kumar','dob': '12/07/1991','gen': 'M','jobType': 'full-time'
};
const arr = ['dob', 'name', 'gen', 'isEmployed', 'jobType'];
const containsAll = (obj, arr) => {
   for(const str of arr){
      if(Object.keys(obj).includes(str)){
         continue;
      }else{
         return false;
      }
   }
   return true;
};
console.log(containsAll(obj, arr));
console.log(containsAll(obj2, arr));

Output

The output of the above code in the console will be −

true
false

Updated on: 19-Aug-2020

413 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements