1

I have an object which I want to loop in. I'm doing the same thing what I'm doing with array but I can't seem to get it done with objects. here:

var friends = {};
friends.bill = {
  firstName: "Bill",
  lastName: "Gates",
  number: "(206) 555-5555",
  address: ['1 Infinite Loop','Cupertino','CA','95014']

};
friends.steve = {
  firstName: "Steve",
  lastName: "Jobs",
  number: "(408) 555-5555",
  address: ['1 Infinite Loop','Cupertino','CA','95014']

};

function search(name){
     for(x=0; x<friends.length; x++){

            if(friends[x].firstName===name){
                    console.log(friends[x]);
                    return friends[x];
                }   
         }

}    

search("Steve");
thinker
  • 91
  • 9

1 Answers1

3

Objects don't have a length, so you use the for in syntax:

function search(name){
    for(var friend in friends){
        if(friends[friend].firstName===name){
            console.log(friends[friend]);
            return friends[friend];
        }   
     }
}    
tymeJV
  • 103,943
  • 14
  • 161
  • 157