Profile Lookup not working for all test cases

Profile Lookup not working for all test cases
0.0 0

#1

Tell us what’s happening:

Your code so far

//Setup
var contacts = [
    {
        "firstName": "Akira",
        "lastName": "Laine",
        "number": "0543236543",
        "likes": ["Pizza", "Coding", "Brownie Points"]
    },
    {
        "firstName": "Harry",
        "lastName": "Potter",
        "number": "0994372684",
        "likes": ["Hogwarts", "Magic", "Hagrid"]
    },
    {
        "firstName": "Sherlock",
        "lastName": "Holmes",
        "number": "0487345643",
        "likes": ["Intriguing Cases", "Violin"]
    },
    {
        "firstName": "Kristian",
        "lastName": "Vos",
        "number": "unknown",
        "likes": ["Javascript", "Gaming", "Foxes"]
    }
];


function lookUpProfile(firstName, prop){
// Only change code below this line
  var isNamePresent=false;
  var nameId=-1;
  var isPropPresent=false;
for(var i=0;i<contacts.length;i++)
  {
     if(contacts[i].firstName === firstName)
      {
        isNamePresent=true;
        nameId=i;
        if(contacts[i][firstName].hasOwnProperty(prop))
          {
            isPropPresent=true;  
          }
      }
  }
  if(isNamePresent===true && isPropPresent===true)
    {
      return contacts[nameId][prop];
    }
  else if(isNamePresent==false)
    {
      return "No such contact";
    }
  else if(isPropPresent==false)
    {
      return "No such property";
    }
// Only change code above this line
}

// Change these values to test your function
lookUpProfile("Akira", "likes");

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36.

Link to the challenge:

Blockquote My Code is not working for all test cases don’t know whats wrong please help.


#2

You have a problem in the following line:

if (contacts[i][firstName].hasOwnProperty(prop)) {

contacts[i] represents one of the objects in the contact array. contacts[i][firstName] will be undefined for all iterations of the for loop, because it is trying to find an “Akira” property of the current object. Since undefined does not have a hasOwnProperty property, you get a TypeError.

Why? Because, firstName is a variable and when you use bracket notation with a variable, it takes on the variables assigned value, which in this case is the firstName argument passed into the function.

You could try contacts[i].hasOwnProperty(prop) and that would not be an error.


#3

Thanks, now I got the problem.