0

The search function in the following code is not working and I believe it has something to do with the For...In loop but I am new to JS and unsure why:

var friends = {
bill: {
    firstName: "bill",
    lastName: "smith",
    number: 1,
    address: ["1"]
},
steve: {
    firstName: "steve",
    lastName: "smith",
    number: 2,
    address: ["2"]
}
};

var list = function(list) {
for(var item in list) {
    console.log(item);
}
};

var search = function(name) {

for(var friend in friends) {
    if(friend.firstName === name) {
        console.log(friend);
        return friend;
    }
}
};

search("steve");
1

2 Answers 2

2

The for in loop iterates over keys, not values.

friend is a string holding the name of each property.
To get the value, use friends[friend].

Sign up to request clarification or add additional context in comments.

Comments

0

Great documentation of the for..in loop can be found on mdn. Where variable is assigned through each iteration to "a different property name".

You also may not need to loop through each friend. What if you changed your search function to use hasOwnProperty on the object:

var search = function(name) {
    if(friends.hasOwnProperty(name)){
        return friends[name];
    }
};

This would check that you have a property of name in the object friends and return it. Here's a quick EXAMPLE.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.