7. Search For a friend


#1
var friends={
    bill:{
        firstName: "Bill",
        lastName: "Gates",
        number: "+91-(819)7-882-503",
        address: [701, "SunnyWale", "CA"]
        },
    steve:{
        firstName: "Steve",
        lastName: "Jobs",
        number: "+91-(959)1-701-993",
        address: [302, "California", "SF"]
        }
    };
    var list = function(friends){
    for (var steve in friends) {
        console.log(steve);

    };
}
var search= function(friends){
    for(var steve in friends){
        if(friends[steve].firstName===friends){
            console.log(friends[steve]);
            return friends[steve];
        }
    }
};

Where am I making the mistake?


#2

Parameters, mostly. Let's consider the list() fun ction, first. When we hand the function a named object and use the same name in the parameter, the function is dedicated to that one object, and no others, since none can be seen by the function.

var list = function (object) {
    for (var key in object) {
        console.log(key);
    }
};
list(friends);

We can use any name we wish for the local variable, so long as it does not exist already in global scope. Reference objects are funny that way. Their variables cannot be shadowed the way ordinary values can.

The search() function, now. Again, it is a quesiton of parameters. We would not, for instance, hand our entire database as a single object to search for. By making it the parameter of your search function that's what you did. Won't function as expected, I'm afraid.

In this case we're handing the function a first name, and the object is accessed as a global, not as a parameter. The function can see it.

var search = function (name) {

};
search("Bill");

Inside the function we want to keep everything generic so it doesn't overlap with known property names. I like to use the variable key for this purpose.

    for (var key in friends) {                 /* friends is global, key is local */
        if (friends[key].firstName === name) {
            console.log(friends[key]);
            return friends[key];
        }
    }

#3

What's the difference between a key and a name?

I'm using steve as both since the friends object carrying Steve's contact details is named steve.

friends.steve = {
    firstName: "Stephen",
    lastName: "Work",
    number: "07086994594",
    address: ['Abakpa', 'Nike', 'Lake']
    };


function search (steve) {
    for (var steve in friends) {
    if (friends[steve].firstName === steve) {
        console.log(friends[steve]);
        return friends[steve];
        }
        }
    }

7. It won't return steve contact information
#4

Okay, to get this straight to you, I'll start with this first:

These are the properties/keys, not the name.

This:

Is an object made used with the variable friends.


It's like a tree:

Friends > Steve > Key/Property


#5

OK. I'm familiar with the name "properties" and not keys. thanks for stopping by


#6