Skip to content

Instantly share code, notes, and snippets.

/arrayOfObjects.js Secret
Created Aug 2, 2017

Embed
What would you like to do?
Is there a more efficient way to access the array of object?
/*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 array of objects
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) {
/*
Input first name and property.
Return:
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"
else Return "prop" relating to firstName.
Assumptions: All firstnames are unique
*/
let loop = 0;
let result = "No such contact";
let firstNameFound = false;
for(loop; loop < contacts.length; loop++){
if (contacts[loop].firstName == firstName){
firstNameFound = true;
break;
};
};
if ((firstNameFound == true) && (contacts[loop][prop] == undefined)){
result = "No such property";
} else if((firstNameFound == true) && (contacts[loop][prop] != undefined)) {
result = contacts[loop][prop];
};
return(result);
};
//Test Cases
console.log(lookUpProfile("Andrew", "likes")); // no such contact
console.log(lookUpProfile("Akira", "likes")); // array returned
console.log(lookUpProfile("Sherlock", "likes")); // array returned
console.log(lookUpProfile("Kristian", "lastName" )); // vos
console.log(lookUpProfile("Kristian", "address" )); // no such property
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.