简体   繁体   中英

Javascript Profile Lookup function

Here is what I want to achieve:

*The function should check if firstName is an actual contact's firstName and the given property (prop) is a property of that contact.

If both are true, then return the "value" of that property.

If firstName does not correspond to any contacts then return "No such contact"

If prop does not correspond to any valid properties then return "No such property"*

My code:

//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(firstName, prop){
// Only change code below this line
  for (var i = 0; i<prop.length; i++){
if(contacts.hasOwnProperty(firstName)=== true && contacts.hasOwnProperty(prop)=== true){

  return firstName[i].prop;
}
  else if(firstName !==firstName[i].prop)  {
    return "No such contact";
  }
   else if(prop !== "prop"){
     return "No such property";
   }
  }
// Only change code above this line
}

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

You can use Array.prototype.find to filter out the contact with the firstName - see demo below:

 // 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(firstName, prop) { var found = contacts.find(function(e){ return e.firstName === firstName; }); if(!found) { return "No such contact"; } else { if(prop in found) { return found[prop]; } else { return "No such property"; } } } // Change these values to test your function var result = lookUpProfile("Akira", "likes"); console.log(result);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM