Function loopThroughAnimals

Hi I’m having trouble with a question on the practice JavaScript loops. (I’m not able to link the page as it comes up randomly in practice.)

How do I access the objects within the objects: e.g. species: cat within the Scooter key?


> Write a function `loopThroughAnimals()` that takes in an object with properties in the following format: `key: {species: "animal type"}` e.g. `dory: {species: "fish"}`
> Your function should loop through the argument object. It should log to the console each property in the following format: `key : animal type` e.g. `dory : fish`
> ```
> let pets = {  Scooter: {species: "cat"},  Bucket: {species: "fish"},  Blammo: {species: "dog"}} loopThroughAnimals(pets);/*Prints:Scooter : catBucket : fishBlammo : dog*/
> ```

What I have so far:

const loopThroughAnimals = (obj) => {
  for (const key in obj) {
  console.log(`${key}: ${obj[key]}`);

Answer I get:

Scooter: [object Object]
Bucket: [object Object]
Blammo: [object Object]

Any help would be greatly appreciated please see quoted text below for the question:

1 Like

At that point in your loop, you can use dot notation or bracket notation to access the properties of the object

Example (your object doesn’t have this property):

// or

Hi, Thank you for your solution!

putting in the property name gave the required result,

is there a way to log the inner object without knowing the property name?

Yes, there are a few ways. You already used one in your existing code. You could nest another for loop inside your existing loop to then iterate through those properties too. You’d want to use a different name to represent the key for your nested for loop so that you can use both keys to access the values

Here is an example of what that nested for loop could look like. (Blurred out so you can try it first)

    for (const innerKey in obj[key]) {
      console.log(`${innerKey}: ${obj[key][innerKey]}`);
1 Like

I’ll give this a try, Thank you! :smiley: