Ahmed Salah El Din Ahmed Salah El Din - 5 months ago 9
Javascript Question

Accessing Javascript objects inside if conditionals, can that be done?

This is my code from Free Code Camp Challenge "Profile Lookup", I am stuck with this code and my problem is the if conditions, how can get the test case to enter my first if condition?

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
for ( var i = 0; i < contacts.length; i++) {
if ( contacts[i].firstName === firstName && contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
}
else if (firstName !== contacts[i].firstName) {
return "No such contact";
}
else if (contacts[i].hasOwnProperty(prop) === false) {
return "No such property";
}
}
}

lookUpProfile("Harry", "likes");


What I am supposed to get is the value of "likes", which is ["Hogwarts", "Magic", "Hagrid"], and for that to happen, it should enter the first if condition, and there is the problem.

Answer

Your problem is that you're returning early. No matter what, you're always returning the first iteration of the contacts collection if any of the conditions are met. What you need to do is store the answer in a local variable, outside of the loop, and return that value. Doing so assures that you've gone through all iterations without returning prematurely.

Try this:

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) {
  var result = undefined;
  for (var i = 0; i < contacts.length; i++) {
    if (contacts[i].firstName === firstName) {
      result = contacts[i];
    } 
  }

  if (result === undefined) {
    return "No such contact";
  }
  if (result.hasOwnProperty(prop) === false) {
    return "No such property";
  }

  return result[prop];
}

console.log(lookUpProfile("Harry", "likes"));

A more functional and idiomatic way would be to use an array method such as filter.