JavaScript Nested objects and arrays in objects

Some objects can contain other objects as properties. For example, there is a country object that can have a number of properties. One of these properties can represent the capital. But at the capital, we can also highlight our properties, for example, the name, population, and year of foundation:

var country = {
 
    name: "Germany",
    language: "Deutsch",
    capital:{
     
        name: "Berlin",
        population: 3375000,
        year: 1237
    }
};
console.log("Capital city: " + country.capital.name); // Берлин
console.log("Population: " + country["capital"]["population"]); // 3375000
console.log("Year of foundation: " + country.capital["year"]); // 1237

To access the properties of such nested objects, we can use the standard dot notation:

country.capital.name

Or access them as array elements:

country["capital"]["population"]

We also allow a mixed type of treatment:

country.capital["year"]

Arrays can also be used as properties, including arrays of other objects:

var country = {
 
        name: "Switzerland",
        languages: ["German", "French", "Italian"],
        capital:{
         
            name: "Bern",
            population: 126598
        },
        cities:[
            { name: "Zurich", population: 378884},
            { name: "Geneva", population: 188634},
            {name: "Basel", population: 164937}
        ]
    };
    
 
// output all elements from country.languages
document.write("<h3>Official languages ​​of Switzerland</h3>");
for(var i=0; i < country.languages.length; i++)
document.write(country.languages[i] + "<br/>");
        
// output all elements from country.cities
document.write("<h3>Cities of Switzerland</h3>");
for(var i=0; i < country.cities.length; i++)
document.write(country.cities[i].name + "<br/>");

The country object has the property of a language that contains an array of strings, as well as a city property that stores an array of objects of the same type.

We can work with these arrays in the same way as with any others, for example, iterate over using the for a loop.

When iterating over an array of objects, each current element will represent a separate object, so we can access its properties and methods:

country.cities[i].name

As a result, the browser will display the contents of these arrays: