hi I am trying to check if a contact exist and if it has a specific property and then return it
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 lookUp(firstName, prop) {
var i;
for (i = 0; i < contacts.length; i++) {
if (contacts[i].firstName === firstName && contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else if (contacts[i].firstName !== firstName) {
return "No such contact";
} else if (contacts[i].firstName === firstName && contacts[i].hasOwnProperty(prop) === false) {
return "No such property";
}
}
}
lookUp("Harry", "likes");
the problem is that it only returns the first result in the loop so in this case it will only check if in contacts[0] firstName===firstName and then return false even if contacts[1] firstName===firstName
Try this:
// Returns:
// contact prop if: contact with prop found
// true if: contact found, but not prop
// false if: not contact found
function lookUp(firstName, prop) {
var i, nameFound = false;
// Starts a loop that looks every contact until the list ends or until firstName with prop is found
for (i = 0; i < contacts.length; i++) {
if (contacts[i].firstName === firstName ) {
// If found, the function return the property "prop" of the contact named "firstName"
// Note that if there is 2 persons with the same name and both has prop, it returns the first one on the list
if(contacts[i].hasOwnProperty(prop)){
return contacts[i][prop];
}
else{
nameFound = true;
}
}
}
// If the script reach this place, it's because the person wasn't found or was found but hasn't the prop
return nameFound;
}
function lookUp(firstName, prop) {
var i;
for (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";
}
}
}
return "No such Contact";
}
To check if an object has a property you can just chek if(obj[prop])
. I like reduce for this kinds of things:
function lookUp (firstName, prop) {
return contacts.reduce(
function (found, contact) {
if (contact[prop] && contact.firstName === firstName)
found.push(contact);
return found;
}, []
);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.