please ignore if this is a silly question to you. I just came up with my own solution to a problem, but I know its not a good solution and there are better smarter ways to do this, please answer if you have other solutions using javascript only.
Its asking to make a function to loop through an array of objects, and return the prop of the object if firstName matches the profile. Return some statements if firstName or prop provided to the function not found.
var contacts = [
{
"firstName": "Sherlock",
"lastName": "Holmes",
"number": "0487345643",
"likes": ["Intruiging Cases", "Violin"]
},
{
"firstName": "Akira",
"lastName": "Laine",
"number": "0543236543",
"likes": ["Pizza", "Coding", "Brownie Points"]
},
{
"firstName": "Harry",
"lastName": "Potter",
"number": "0994372684",
"likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
"firstName": "Kristian",
"lastName": "Vos",
"number": "unknown",
"likes": ["Javascript", "Gaming", "Foxes"]
},
];
function lookUp(firstName, prop){
for (var i = 0; i < contacts.length; i++){
var n = parseInt(contacts.length);
if (contacts[i].firstName === firstName) {
if (contacts[i].hasOwnProperty(prop)){
return contacts[i][prop];
}
else return "No such property";
}
else if (i === (n-1)) {
return "No such contact";
}
}
}
console.log(lookUp("Sherlock", "likes"));