I have an object
var friends = { bill: { firstName: "A", lastName: "C", number: "999", }, }; How can I print the values of the object friends using a for...loop?
var friends = { bill: { firstName: "A", lastName: "C", number: "999", }, print: function () { for (var p in this.bill) console.log(p + ' ' + this.bill[p]); } }; This code will print, is that what you need?
friends.print(); I'm going to make a suggestion that might make your coding a little easier. Instead of using an object to contain a list of friends, use an array instead. An array is a list after all, and Javascript comes with some really useful array functions that can help you in the long run.
var friends = [ { name: 'Bill Z', firstName: "Bill", lastName: "X", number: "999", }, { name: 'Sam Y', firstName: "Sam", lastName: "Y", number: "999", } ]; To get the list of friends you might use a couple of loops; one to loop over the list of objects, and one to loop over the properties of each object:
function listFriends() { for (var i = 0, l = friends.length; i < l; i++) { for (var p in friends[i]) { console.log(p + ': ' + friends[i][p]); } } } Or to get HTML out:
function listFriends() { var html = ''; for (var i = 0, l = friends.length; i < l; i++) { html += '<b>' + friends[i].firstName + '</b><br/>'; for (var p in friends[i]) { html += p.toUpperCase() + ': ' + friends[i][p] + '<br/>'; } } return html; } You might also like to access the list of friends to find one in particular. In this example I use filter.
function getFriend(prop, value) { return friends.filter(function (obj) { return obj[prop] === value; }); } console.log(getFriend('firstName', 'Sam')) // { name="Sam Y", firstName="Sam", lastName="Y"} Hopefully you'll find some of this useful.
If you'd like to print only the members of within friends.bill, you might want to use a for..in loop, for example:
for(var p in friends.bill) console.log(p + ": " + friends.bill[p]) Which will print this in the console:
firstName: A VM579:3 lastName: C VM579:3 number: 999
friends.bill.firstNameetc?friends? Do you want to print their properties/values to the console or add them to a DOM element?for...loopis and in my first comment I showed you how to access the values. What else do you need?