Last active
May 19, 2017 16:33
-
-
Save rodpoblete/51e0d5d107e555a173f9467f4bbee0ed to your computer and use it in GitHub Desktop.
Profile Lookup Problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// We have an array of objects representing different people in our contacts lists. | |
// A lookUpProfile function that takes firstName and a property (prop) as arguments has been pre-written for you. | |
// 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" | |
/* | |
//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){ | |
for (var 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"; | |
} | |
/* Explicación del código: | |
- El bucle for se ejecuta, comenzando en el primer objeto de la lista de contactos. | |
- Si el parámetro firstName pasó a la función y coincide con el valor de la clave "firstName" en el primer objeto, se pasa la instrucción if. | |
- Luego, usamos el método .hasOwnProperty () (comprueba si hay una propiedad dada y devuelve un booleano) con prop como argumento. Si es cierto, se devuelve el valor de prop. | |
- Si la segunda instrucción if falla, no se devuelve tal propiedad. | |
- Si la primera instrucción if falla, el bucle for continúa con el siguiente objeto de la lista de contactos. | |
- Si el parámetro firstName no coincide con el objeto de contactos final, el bucle for se cierra y no se devuelve tal contacto. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment