* fix: restructure certifications guide articles * fix: added 3 dashes line before prob expl * fix: added 3 dashes line before hints * fix: added 3 dashes line before solutions
1.7 KiB
1.7 KiB
title
| title |
|---|
| Check if an Object has a Property |
Check if an Object has a Property
Solutions
Solution 1 (Click to Show/Hide)
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) {
if (
obj.hasOwnProperty("Alan") &&
obj.hasOwnProperty("Jeff") &&
obj.hasOwnProperty("Sarah") &&
obj.hasOwnProperty("Ryan")
) {
return true;
}
return false;
}
Code Explanation
- Checks whether object contains all users by using the
hasOwnPropertymethod for each name with the&&operator to return atrueorfalsevalue.
Solution 2 (Click to Show/Hide)
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 ["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
everymethod is used to validate all of names used in conjunction with thehasOwnPropertymethod result in a value oftruebeing returned during each iteration. - If at least one name is not found using the
hasOwnPropertymethod, theeverymethod returnsfalse.