So, I go through freecodecamp and I solve problems there to keep in a loop with programming, and I came across a trap, and I'm not quite sure what happened.
So, I have an array of objects called contacts, and I need to create a function called lookUp(firstName, prop). The text of the task is as follows:
The function should check if the firstNameactual contact is firstName, and this property ( prop) is a property of this contact.
If both values are true, return the "value" of this property.
If it firstNamedoes not match any contacts, then return "No such contact"
If it propdoes not match any valid properties, return "No such property"
Code:
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": ["Intruiging Cases", "Violin"]
},
{
"firstName": "Kristian",
"lastName": "Vos",
"number": "unknown",
"likes": ["Javascript", "Gaming", "Foxes"]
},
];
function lookUp( firstName, prop ){
for( var i = 0; i < contacts.length; i++ ){
if( contacts[i].firstName == firstName ) {
if( contacts[i].hasOwnProperty( prop ) ) {
return contacts[i].prop;
} else {
return "No such property";
}
} else {
return "No such contact";
}
}
}
lookUp("Kristian", "lastName");
So, I go through an array with a loop forchecking each object. In the first, ifI check if the property of firstNamethis object is equal to the parameter of the firstName function, then if it is true, I check if the object has a property prop, and I should be able to return it. But it seems that
return contacts[i].prop;
not working and i'm a little lost why. I'm sure this is something trivial, but I don’t understand why. When I go to the console and test
contacts[0].likes
I exit the array ["Pizza", "Coding", "Brownie Points"], but in my case, if this does not work. What am I doing wrong here?
EDIT
Ok so i tried
function lookUp( firstName, prop ){
for( var i = 0; i < contacts.length; i++ ){
if( contacts[i].firstName == firstName ) {
if( contacts[i].hasOwnProperty( prop ) ) {
return contacts[i][prop];
} else {
return "No such property";
}
} else {
return "No such contact";
}
}
}
But I still get the same error: \