2018-10-12 15:37:13 -04:00
---
title: Check if an Object has a Property
---
2019-07-24 00:59:27 -07:00
# Check if an Object has a Property
2018-10-12 15:37:13 -04:00
2019-07-24 00:59:27 -07:00
---
## Solutions
< details > < summary > Solution 1 (Click to Show/Hide)< / summary >
```javascript
2018-10-12 15:37:13 -04:00
let users = {
Alan: {
age: 27,
online: true
},
Jeff: {
age: 32,
online: true
},
Sarah: {
age: 48,
online: true
},
Ryan: {
age: 19,
online: true
}
};
function isEveryoneHere(obj) {
2019-05-28 13:04:08 -07:00
if (
2019-07-24 00:59:27 -07:00
obj.hasOwnProperty("Alan") & &
obj.hasOwnProperty("Jeff") & &
obj.hasOwnProperty("Sarah") & &
obj.hasOwnProperty("Ryan")
2019-05-28 13:04:08 -07:00
) {
2018-10-12 15:37:13 -04:00
return true;
}
return false;
}
2019-05-28 13:04:08 -07:00
```
2018-10-12 15:37:13 -04:00
2019-05-28 13:04:08 -07:00
#### Code Explanation
2018-10-12 15:37:13 -04:00
2019-05-28 13:04:08 -07:00
* Checks whether object contains all users by using the `hasOwnProperty` method for each name with the `&&` operator to return a `true` or `false` value.
2019-07-24 00:59:27 -07:00
< / details >
< details > < summary > Solution 2 (Click to Show/Hide)< / summary >
2018-10-12 15:37:13 -04:00
```javascript
2019-05-28 13:04:08 -07:00
let users = {
Alan: {
age: 27,
online: true
},
Jeff: {
age: 32,
online: true
},
Sarah: {
age: 48,
online: true
},
Ryan: {
age: 19,
online: true
}
};
2018-10-12 15:37:13 -04:00
function isEveryoneHere(obj) {
2019-07-24 00:59:27 -07:00
return ["Alan", "Jeff", "Sarah", "Ryan"].every(name =>
obj.hasOwnProperty(name)
);
2018-10-12 15:37:13 -04:00
}
```
2019-05-28 13:04:08 -07:00
#### Code Explanation
* Uses an array with all of the names which should be present in the object.
* The `every` method is used to validate all of names used in conjunction with the `hasOwnProperty` method result in a value of `true` being returned during each iteration.
* If at least one name is not found using the `hasOwnProperty` method, the `every` method returns `false` .
#### Relevant Links
* [Array.prototype.every ](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every )
2019-07-24 00:59:27 -07:00
< / details >