# Nested Loops for Complex Objects

There will be times when you have a complex object that has arrays nested inside of arrays. When you need to loop through all of the elements at every level, we will use a nested loop.

Take this data as our example:

var pets = {
  animals: [
    { dogs: ["Woody", "Roxy"] },
    { cats: ["Willow", "Jesse Pink-kitty", "Bob"] }
  ]
};
1
2
3
4
5
6

In this object, animals is an array of objects. Each of the objects inside of animals has a property which is an array.

We want to be able to write out all these pet names dynamically in a format that looks like this:

dogs
    Woody
    Roxy
cats
    Willow
    Jesse Pink-kitty
    Bob
1
2
3
4
5
6
7

So, a nested loop... That means a loop inside of a loop.

NOTE: In the outer loop we are declaring two variables a and numAnimals in the first part of the loop conditions. This is not something special for nested loops. You can do this with any for...loop.

let animals = pets.animals; //our first array
for (let a = 0, numAnimals = animals.length; a < numAnimals; a++) {
  for (let prop in animals[a]) {
    //this will only loop once and get us the property name
    console.log(prop);
    //now get all the pet names for this prop (dogs or cats)
    for (let i = 0, numPets = animals[a][prop].length; i < numPets; i++) {
      console.log("\t", animals[a][prop][i]);
      //add the \t to indent one tab
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12

Here we used a loop inside a loop inside a loop. The second loop was necessary because our array was hidden behind a property name. If we only had an array of arrays then two loops would be all that was required.

Back to Week 7 main page

Last Updated: 6/13/2020, 11:30:19 PM