-2

I have taken a course and I got a project here.

    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){

    }

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

So "Kristian", "lastName" should return "Vos" And "Sherlock", "likes" should return ["Intriguing Cases", "Violin"] I am confused what to do here 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" I want to know the part about how do I check if the name exists.

K.A. Siddiqui
  • 49
  • 1
  • 8

2 Answers2

1

You can use Array.prototype.find() for this. Note that it will only return the first match - so if you have multiple persons with the same name (not given in your example), you'd have to switch to filter()

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) {
  let profile = contacts.find(contact => contact.firstName === firstName);
  if (!profile) return "No such contact";
  return profile[prop] || "No such property";
}

// Change these values to test your function
console.log(lookUpProfile("Akira", "likes"));
baao
  • 71,625
  • 17
  • 143
  • 203
0

You can use lodash like so,

function lookUpProfile(firstName, prop) {

  return _(contacts)
  .filter(c => c.firstName === firstName)
  .map(prop)
  .value();
}

You said you would handle the 'No such contact' yourself, which you can easily do by storing the result of the query in a variable and checking the variable. Credit to this answer:

Community
  • 1
  • 1
Latin Warrior
  • 902
  • 11
  • 14