Refactoring Profile Lookup

Refactoring Profile Lookup
0

#1

I have successfully passed all the tests with this code, but it seems very messy. Can anyone suggest something more elegant or optimized?

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

  for (var i = 0; i < contacts.length; i++) {
    if (contacts[i]["firstName"] === name && contacts[i].hasOwnProperty(prop)) {
      return contacts[i][prop];
    }
  }

  for (var i = 0; i < contacts.length; i++) {
    if (contacts[i]["firstName"] === name) {
      break;
    }
    return "No such contact";
  }

  for (var i = 0; i < contacts.length; i++) {
    if (contacts[i].hasOwnProperty(prop)) {
      continue;
    }
    return "No such property";
  }

}

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/profile-lookup/


#2

Seeing how it’s in an array, maybe you can use functions such as Array.prototype.filter().


#3

Probably something like this

function lookUpProfile(name, prop){
    let contact = contacts.filter(obj => obj.firstName == name)[0];
    
    if(!contact){ return "No such contact";  }

    let property = contact[prop];
    
    if(!property){ return "No such property";  }

    return property;
}

#4

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, if you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

Thank you.