DEV Community

loading...

Profile Lookup

rthefounding profile image Randy Rivera ・1 min read
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"]
    }
];
Enter fullscreen mode Exit fullscreen mode
function lookUpProfile(name, prop) {
  for (let i = 0; i < contacts.length; i++) {
    if (contacts[i].firstName === name) {
       if (contacts[i].hasOwnProperty(prop)) {
        return contacts[i][prop];
      } 
        return "No such property";
     }
  }
  return "No such contact";
}

console.log(lookUpProfile("Kristian", "lastName")); will display Vos
Enter fullscreen mode Exit fullscreen mode

Problem Explanation:

  • This function includes two parameters, firstName and prop.
  • The function looks through the contacts list for the given firstName parameter and to do so we will use a for loop to cycle through the contacts list.
  • If there is a match found, the function then should look for the given prop parameter.
  • If both firstName and the associated prop are found, you should return the value of the prop. We use a nested if statement to first check if the firstName matches, and then checks if the prop matches.
  • If firstName is found and no associated prop is found, you should return No such property.
  • If firstName isn’t found anywhere, you should return No such contact.

Discussion (0)

Forem Open with the Forem app