Lesson Monday

Let's learn how to create an object that contains another object, then we'll use this to build out an address book.

We'll begin by making some objects that represent cities and countries:

var pdx = { name: "Portland" };
var sfo = { name: "San Francisco" };
var sea = { name: "Seattle" };
var cso = { name: "Aktau" };
var dzn = { name: "Zhezkazgan" };

var usa = { name: "United States of America" };
var kazakhstan = { name: "Kazakhstan" };
var uruguay = { name: "Uruguay" };

Very often, we'll want to create associations between objects; for example, we may want to know a list of cities in a particular country. Here's how we can do this:

var pdx = { name: "Portland" };
var sfo = { name: "San Francisco" };
var sea = { name: "Seattle" };
var cso = { name: "Aktau" };
var dzn = { name: "Zhezkazgan" };

var usa = { name: "United States of America", cities: [pdx, sfo, sea] };
var kazakhstan = { name: "Kazakhstan", cities: [cso, dzn] };
var uruguay = { name: "Uruguay", cities: [] };

It's very common to have a property of an object that's an array with other objects contained within it. Now we can do things like list all of the cities we know about for a country:

usa.cities.forEach(function(city) {
  console.log("Let's go to " + city.name + "!");
});

We can also add cities to a country after the object is initially created:

var mlz = { name: "Melo" };
uruguay.cities.push(mlz);

uruguay.cities returns an array, and then we push() the new object onto the array.

Let's look at one more example before applying this to our address book:

var tomatoes = { name: "Tomatoes", price: 2.99 };
var cucumbers = { name: "Cucumbers", price: 0.99 };
var onions = { name: "Onions", price: 0.79 };

var groceryStore = { name: "Michael's corner market", products: [tomatoes, cucumbers, onions] };

var iPhone = { name: "iPhone", price: 699 };
var android = { name: "Android", price: 499 };
var windowsPhone = { name: "Windows Phone", price: 399 };

var phoneStore = { name: "RadioShack", products: [iPhone, android, windowsPhone] };

var stores = [groceryStore, phoneStore];

stores.forEach(function(store) {
  console.log(store.name + " sells:");
  store.products.forEach(function(product) {
    console.log(product.name);
  });
  console.log("\n");
});

Here, we're looping through each store and displaying its name, and then within each store, looping through each of its products and displaying their names.

Examples


To create relationships among objects, use properties whose values are arrays of other objects:

var pdx = { name: "Portland" };
var sfo = { name: "San Francisco" };
var sea = { name: "Seattle" };

var usa = { name: "United States of America", cities: [pdx, sfo, sea] };

For consistency, when using similar objects, use an empty array rather than not defining the property:

var uruguay = { name: "Uruguay", cities: [] };

Add more objects to the array property:

var mlz = { name: "Melo" };
uruguay.cities.push(mlz);