Profile Lookup // problems with hasOwnProperty (?)

Profile Lookup // problems with hasOwnProperty (?)
0

#1

Tell us what’s happening:
Hey, I have a problem with a middle part of the challenge.
I can’t understand why my code doesn’t give back the
existing property value.
The answer given in the hints section quite different
and I would like to understand my mistake.

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(name, prop){
// Only change code below this line
for (var i = 0; i < contacts.length; i++){
    if (name !== contacts[i].firstName) {
        return "No such contact"
    }
    else if (contacts[i].hasOwnProperty(prop))
    {return contacts[i][prop]}
    else {return "No such property"}
}
// Only change code above this line
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/profile-lookup/


#2

At the first instance that the loop finds a contact that does not match the firstName property, what your line above does is exit the function entirely without checking for the rest of the objects in the array, so what you want to do, is make sure that ALL the objects in the array do not match the name before you return “No such contact”, see if you can fix that logic first and then deal if the object with the matching name (if it exists) has the property you are looking for.


#3

Thank you! :slight_smile: