Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
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
true false
Optimized Approach Using hasOwnProperty()
A more efficient approach uses the `hasOwnProperty()` method instead of creating an array with `Object.keys()` and checking with `includes()`:
const containsAllOptimized = (obj, arr) => {
for(const key of arr){
if(!obj.hasOwnProperty(key)){
return false;
}
}
return true;
};
const testObj = {
name: 'John',
age: 30,
city: 'New York'
};
const requiredKeys = ['name', 'age'];
const missingKeys = ['name', 'age', 'country'];
console.log(containsAllOptimized(testObj, requiredKeys));
console.log(containsAllOptimized(testObj, missingKeys));
true false
Using Array.every() Method
An even cleaner approach uses the `Array.every()` method for a more functional programming style:
const containsAllEvery = (obj, arr) => {
return arr.every(key => obj.hasOwnProperty(key));
};
const person = {
firstName: 'Alice',
lastName: 'Smith',
email: 'alice@example.com'
};
console.log(containsAllEvery(person, ['firstName', 'email']));
console.log(containsAllEvery(person, ['firstName', 'phone']));
true false
Comparison
| Method | Performance | Readability | Early Exit |
|---|---|---|---|
| Object.keys() + includes() | Slower | Good | Yes |
| hasOwnProperty() loop | Fast | Good | Yes |
| Array.every() | Fast | Excellent | Yes |
Conclusion
Use `Array.every()` with `hasOwnProperty()` for the cleanest and most efficient solution. The `Object.keys()` approach works but creates unnecessary arrays, making it less performant for large objects.
