fix: corrected guide solutions and explanations (#36125)
This commit is contained in:
committed by
Parth Parth
parent
bd065c1a0e
commit
ad3d0aed04
@ -3,13 +3,7 @@ title: Check if an Object has a Property
|
||||
---
|
||||
## Check if an Object has a Property
|
||||
|
||||
Method:
|
||||
- The simplest way to complete this challenge is to create an `ìf-statement` to check wether or not the object contains all users, then to return a true or false statement. The first solution does just this.
|
||||
- The second solution works in exactly the same way, only it uses 1 line of code - `Conditional(ternary)-Operator` - within the function.
|
||||
|
||||
[developer.mozilla.org](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) provides a more in depth analysis of the ternary operator.
|
||||
|
||||
### Solution-1:
|
||||
### Basic Solution:
|
||||
```javascript
|
||||
|
||||
let users = {
|
||||
@ -32,23 +26,57 @@ let users = {
|
||||
};
|
||||
|
||||
function isEveryoneHere(obj) {
|
||||
// change code below this line
|
||||
if(users.hasOwnProperty('Alan','Jeff','Sarah','Ryan')) {
|
||||
if (
|
||||
obj.hasOwnProperty('Alan') && obj.hasOwnProperty('Jeff') &&
|
||||
obj.hasOwnProperty('Sarah') && obj.hasOwnProperty('Ryan')
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
// change code above this line
|
||||
}
|
||||
|
||||
console.log(isEveryoneHere(users));
|
||||
|
||||
```
|
||||
|
||||
### Solution-2:
|
||||
#### Code Explanation
|
||||
|
||||
* Checks whether object contains all users by using the `hasOwnProperty` method for each name with the `&&` operator to return a `true` or `false` value.
|
||||
|
||||
### Advanced Solution:
|
||||
```javascript
|
||||
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) {
|
||||
return (users.hasOwnProperty('Alan','Jeff','Sarah','Ryan')) ? true : false;
|
||||
return [
|
||||
'Alan',
|
||||
'Jeff',
|
||||
'Sarah',
|
||||
'Ryan'
|
||||
].every(name => obj.hasOwnProperty(name));
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
#### 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)
|
||||
|
Reference in New Issue
Block a user