Tell us what’s happening:
Hello, can someone help me with this little JS things?
I have a problem with looping data, I already test in JS Fiddle, now I know what’s the problem, but I didn’t know how to fix this.
Your code so far
// 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(name, prop){
// Only change code below this line
for (let i = 0; i < contacts.length; i++){
if (contacts[i].firstName === name && contacts[i].hasOwnProperty(prop)){
return contacts[i][prop]
} else if (contacts[i].firstName !== name){
return "No such contact";
} else if (!contacts[i].hasOwnProperty(prop)){
return "No such property";
} else {
return "Error";
}
}
// Only change code above this line
}
lookUpProfile("Akira", "likes");
Your browser information:
User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36.
Remember that a return statement always ends function execution. In your code, a return statement is always going to be hit in the first iteration of the loop. That means that only the first value in contacts will be checked.
I already try a different method but didn’t correct it.
I got an error cant to execute No such contact & No such property.
// Only change code below this line
function findName(contacts){
return contacts.firstName === name;
}
let checkName = contacts.find(findName).firstName == name;
let checkProp = contacts.find(findName).hasOwnProperty('likes');
if(checkProp && checkName){
return contacts.find(findName)[prop];
} else if (!checkName){
return "No such contact";
} else if (!checkProp){
return "No such property";
}
// Only change code above this line
If i make like this, still error but the error is reverse. I got error on execute correct data.
// Only change code below this line
for(let i = 0; i < contacts.length; i++){
if(contacts[i].firstName !== name){
return "No such contact";
} else if (!contacts[i].hasOwnProperty(prop)){
return "No such property";
}
}
function findName(contacts){
return contacts.firstName === name;
}
let checkName = contacts.find(findName).firstName === name;
let checkProp = contacts.find(findName).hasOwnProperty('likes');
if(checkProp && checkName){
return contacts.find(findName)[prop];
}
// Only change code above this line
for(let i = 0; i < contacts.length; i++){
if (contacts[i].firstName === name){
if (contacts[i].hasOwnProperty(prop)){
return contacts[i][prop];
}
return "No such property";
}
}
return "No such contact";