Check if object contains all keys in JavaScript array

JavascriptWeb DevelopmentObject Oriented Programming

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 −


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){
         return false;
   return true;
console.log(containsAll(obj, arr));
console.log(containsAll(obj2, arr));


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

Published on 19-Aug-2020 10:53:22