I have an array of objects and I want to iterate over them. One object of this array looks like this:
var people = [
{
"firstName": "YYY",
"lastName": "XXX",
"number": "123456789",
"attribute": ["strong", "quick", "stupid"]
},
{
"firstName": "AAA",
"lastName": "BBB",
"number": "9876543210",
"attribute": ["calm", "wise", "slow"]
},
{
"firstName": "CCC",
"lastName": "VVV",
"number": "158974528",
"attribute": ["brutal", "bad", "gentle"]
}
and so on (around 20 objects in array).
And so on. I try to write a function which checks if the firstName exists in my people array and if the property is attribute of that contact. So if I call the function with attributes:
lookUpProfile("YYY", "lastName");
It should return me the value of attribute of this object.
In that case: ["strong", "quick", "stupid"]
What it actually does is that my function checks only the first object and then stops...So it works only if i call this function with arguments which matches the first object in array. If I call the function like this:
lookUpProfile("CCC", "number");
It returns me "No Such contact". What's wrong here so the loop checks only the first object?
Here is the code of function:
function lookUpProfile(firstName, attribute){
for (i = 0; i < people.length; i++) {
if (firstName == people[i].firstName && firstName == people[i].firstName) {
return (people[i][attribute]);
}
else {
return "No such contact";
}
}
Thanks for all reply! It helps a lot. But I forgot to mention about one thing. I want also to check if the given property (attribute) exists in object.
So if I call the function lookUpProfile("YYY", "YourAGE");
It shall return me "No such property";
My function looks now like this:
function lookUpProfile(firstName, prop){
for (i = 0; i < people.length; i++) {
if (firstName == people[i].firstName && people[i].hasOwnProperty(prop))
return (people[i][prop]);
else if(firstName != people[i].firstName) {
return "No such contact";
}
else if(people[i].hasOwnProperty(attribute) == false) {
return "No such property";
}
}
return "No such contact";
Thanks You all! I got the working solution. Last question: can You explain only this line: if (firstName == people[i].firstName) firstNameFound = true;? I don't understand this line - why is the variable called after IF statement? ;).
if ( ... )isn't fulfilled? What's the purpose of the keywordreturn?["strong", "quick", "stupid"]" should be "In that case:"XXX""