samedi 10 mars 2018

Nested IF inside FOR loop works only for first value

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 (aroung 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 wich 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";
    }
   }
  }

Aucun commentaire:

Enregistrer un commentaire