thomas101rcx
thomas101rcx

Reputation: 29

Javascript Search Function Error

I am writing a search function within my Javascript code. However, it keeps on returning search function doesn't return correct contact information.

The goal of this search function is to return the contact information of the object , ie, firstName , lastName , number and address. If given an input Name , it matches one of the keys in the object I created, it should return the contact information and log it on the console.

var friends = {
    bill:{
        firstName : "Bill",
        lastName : "Gates",
        number : "(123) 456- 7890", 
        address : ['Microsoft', 20]
        },
    steve:{
        firstName : "Steve",
        lastName : "Jobs",
        number : "(123) 456- 7890",
        address : ['Apple', 30]
        }      
};
var friends1 = new Object();
var list =  function(friends1){
    for(var key in friends1){
        console.log(friends1[key].firstName.toLowerCase());   
    }  
};

var search = function(name){
 for(var key in friends1){
     if(friends1[key].firstName.toLowerCase() === name.toLowerCase()){
        console.log(friends1[key]);
        return friends1[key];
        }
 }   
};
list(friends1);
search("Steve");

Upvotes: 1

Views: 129

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075735

In your search function, you loop through the keys in friends1. The friends1 that search closes over is the one from:

var friends1 = new Object();

...that you never add any properties to. So the loop won't do anything; there are no enumerable properties in the object you're querying.

Throughout search, you want friends, not friends1:

var friends = {
    bill:{
        firstName : "Bill",
        lastName : "Gates",
        number : "(123) 456- 7890", 
        address : ['Microsoft', 20]
        },
    steve:{
        firstName : "Steve",
        lastName : "Jobs",
        number : "(123) 456- 7890",
        address : ['Apple', 30]
        }      
};
var friends1 = new Object();

var search = function(name){
 for(var key in friends){
     if(friends[key].firstName.toLowerCase() === name.toLowerCase()){
        console.log(friends[key]);
        return friends[key];
     }
 }   
};
search("Steve");

Upvotes: 2

Related Questions