Some Background Information
There was a lesson on Codecademy that instructed me to create a contact list (features objects within objects). At the end, I was to make a function that could take an input and match it with any names on the contact list. If there was a match, it would log all of the contact information associated with that name to the console.
So far, I have successfully done all of the above and wanted to go a little further. I wanted the function to log the address of the person with spacing in between each value (like this: "One Microsoft Way, Redmond, WA, 98052" instead of "One Microsoft Way,Redmond,WA,98052").
I also wanted the function to log "No match." into the console (just once) if it searched through the entire contact list and found no matching names. With my current code, it logs "No match." for every single non-matching name, and I don't want that.
In short: How can I return and separate an array of values with spacing between each value? How can I make the function return "No match." a single time after not finding any matches?
Here is my code:
// Main object
var friends = {
// Nested objects
bill: {
firstName: "Bill",
lastName: "Pifheba",
number: "1234567890",
address: ["One Microsoft Way", "Redmond", "WA", "98052"]
},
steve: {
firstName: "Steve",
lastName: "Ajfiae",
number: "1234512345",
address: ["2 Stack Way", "Lazss", "WA", "12345"]
},
bob: {
firstName: "Bob",
lastName: "Dcfiwae",
number: "8291047261",
address: ["28 Stack Way", "What", "WA", "54321"]
}
};
// Searches for matching name
var search = function(name) {
// Iterates through nested objects
for (var x in friends) {
// If match is found
if (friends[x].firstName === name) {
// Print contact information
console.log("First Name: " + friends[x].firstName + "\r\nLast Name: " + friends[x].lastName + "\r\nNumber: " + friends[x].number + "\r\nAddress: " + friends[x].address);
} else {
console.log("No match.");
}
}
};
// Asks for who to search for
search(prompt("Name?"));