Home > Net >  Iterate over an interface element of an Interface
Iterate over an interface element of an Interface

Time:01-26

Suppose I have the interfaces:

export interface Animals {
   animals: Animal[]
};

export interface Animal {
    name: string,
    age: number
};

And I wish to iterate over the animals property of Animals. This is the code I tried suppose I have valid JSON:

Animals: Animals = JSONObject.animals;
Animals.animals.forEach((animal, index) => {
    console.log(`Animal Number ${index   1}`);
    console.log(animal);
});

I get the following error TypeError: Cannot read properties of undefined (reading 'forEach').

EDIT: JSON is of the form,

"animals": [
    {
        "name":"Cat",
        "age":12
    },
    {
        "name":"Dog",
        "age":7
    }
]

CodePudding user response:

const Animals: Animals = JSONObject.animals;
Animals.animals.forEach(/* ... */)

You are drilling into .animals twice. Once in the first assignment, and again on the second line.

You only want to do that once.

const Animals: Animals = JSONObject;
Animals.animals.forEach(/* ... */)
  •  Tags:  
  • Related