Search code examples
javascriptbooleanhasownproperty

Basic Data Structures: Check if an Object has a Property


I've been having some trouble with the Free Code Camp lesson on checking if an object has certain properties.

In this lesson, we're supposed to use hasOwnProperty() to check if the users object contains Alan, Jeff, Sarah, and Ryan. If all of the users are present, then return true, otherwise, if any of those users are missing, then the code needs to return false.

I've been trying for over hour and this is kind of where I've ended up, but I can't quite figure out how to get the code to return false when one of the names is removed. I tend to overthink my code, so I might be thinking about it too hard.

Thanks in advance! And sorry if something like this has been asked before. I wasn't able to find anything.

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) {
  // change code below this line
  for (let name in users) {
    if (name === 'Alan' && 'Jeff' && 'Sarah' && 'Ryan') {
      return true;
    } else {
      return false;
    }
  }
  // change code above this line
}

console.log(isEveryoneHere(users));


Solution

  • You don't need to loop through the properties. You should loop through the array of names you're looking for.

    function isEveryoneHere(obj) {
      // change code below this line
      for (let name of required) {
        if (!obj.hasOwnProperty(name)) {
          return false;
        }
      }
      return true;
      // change code above this line
    }
    
    let users = {
      Alan: {
        age: 27,
        online: true
      },
      Jeff: {
        age: 32,
        online: true
      },
      Sarah: {
        age: 48,
        online: true
      },
      Ryan: {
        age: 19,
        online: true
      }
    };
    let users2 = {
      Alan: {
        age: 27,
        online: true
      },
      Jeff: {
        age: 32,
        online: true
      },
      Jane: {
        age: 48,
        online: true
      },
      Ryan: {
        age: 19,
        online: true
      }
    };
    
    const required = ['Alan', 'Jeff', 'Sarah', 'Ryan'];
    
    console.log(isEveryoneHere(users));
    console.log(isEveryoneHere(users2));