Reputation: 625
In this freecodecamp exercise you're supposed to return "No such contact" if an unknown contact is entered. And "No such property" if an invalid property is entered. I'm able to pull various contacts information but i'm confused how to accommodate the tests I just mentioned. Every time I do it screws up my if statement. Any thoughts on 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(name, prop) {
var myStr = '';
for (var i = 0; i < contacts.length; i++) {
if (contacts[i].firstName === name) {
myStr = contacts[i][prop];
}
}
return myStr;
}
lookUpProfile("Harry", "likes");
Upvotes: 0
Views: 43
Reputation: 950
Just go sequentially from check the contact existed or not first If not then return the result: No Profile
Then next check the prop with hasOwnProp then if not exist return: No Prop
Else of them you return the item from find function
// 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){
const result = contacts.find(item => item.firstName === name)
if(!result) return 'No such contact'
if(!result.hasOwnProperty(prop)) return 'No such prop'
return result;
}
console.log(lookUpProfile("Harry1", "likes1"))
console.log(lookUpProfile("Harry", "likes"))
console.log(lookUpProfile("Harry", "likes1"))
Upvotes: 1
Reputation: 1363
To check if an object has a property you should use Object.prototype.hasOwnProperty()
There are several ways of returning "No such contact". One would be to init myStr to "No such contact" instead of an empty string.
Upvotes: 0