I have to write a function that checks to see whether argument 1 (firstName) is a value in the array oj objects stored in variable (contacts) and if it is, return the current objects property value (prop). If firstName is not present, I have to return 'No contact found'. If a prop is not found, I have to return 'No such property'.
I'm having a hard time figuring out how to check whether the argument (firstName) is not found in the object of arrays. How does one write an if statement to check for that?
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",
'youtube': 'nah',
"number": "0487345643",
"likes": ["Intriguing Cases", "Violin"]
},
{
"firstName": "Kristian",
"lastName": "Vos",
"number": "unknown",
"likes": ["Javascript", "Gaming", "Foxes"]
}
];
function lookUpProfile(firstName, prop){
for (i=0;i<contacts.length;i++) {
if (Object.values(contacts[i]).indexOf(firstName) > -1 && contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
}
if (!contacts[i].hasOwnProperty(prop)) {
return 'No such property';
}
}
}
lookUpProfile("Sherlock", "likes");
contacts.find(obj => obj.firstName === firstName)[prop]. Add intermediate truthy checking forNo contacts foundandNo property found"firstName": "Kristian", havefirstName: "Kristian".(contacts.filter(obj => obj.firstName === firstName)[0] || {})[prop] || 'No such property';works in all browsers including IE 9. Although admittedly less readable.