freeCodeCamp Challenge Guide: 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(userObj) {
 return userObj.hasOwnProperty("Alan") &&
    userObj.hasOwnProperty("Jeff") &&
    userObj.hasOwnProperty("Sarah") &&
    userObj.hasOwnProperty("Ryan");
}

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.
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(userObj) {
  return ["Alan", "Jeff", "Sarah", "Ryan"].every(name =>
    userObj.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

91 Likes