Home > Software design >  How to access nested JSON objects in angular?
How to access nested JSON objects in angular?

Time:09-23

My API returns a JSON response my Angular application picks-up using an Interface. The JSON that gets returned looks like this:

    {
       "release_date":"2012-03-14",
       "genre_relation":[
          {
             "id":"2604ebbf-4eb5-46e3-89d8-ab4e8ecc8275",
             "name":"ABC"
          },
          {
             "id":"5267a0c6-9423-4e28-a413-133cc3435612",
             "name":"DEF"
          },
          {
             "id":"13d1454a-fc0e-457c-9f8e-9a9952984d8c",
             "name":"GHI"
          }
       ]
    }

Now my question, How I can access the name field of the response as it nested? For example, if I do the following at my template:

    <p>{{ api_response.genre_relation.name }}</p>

.name is not resolving. Do I have to do this on Interface level? Currently, my Interface looks really flat:

    export interface SomeResponse {
      release_date: string;
      genre_relation: string;
    }

Kind regards and thanks in advance.

CodePudding user response:

genre_relation is an array of objects. So you have to iterate through that array and access each object in the array separately. You can do that with ngFor:

<p *ngFor="let item of api_response.genre_relation">
  {{ item.name }}
</p>

CodePudding user response:

The name field is on an object that is in the array genre_relation.

So you would access it by iterating through the array and then display or by index such as

api_response.genre_relation[0].name

CodePudding user response:

You should have the interface for the objects you have in your json. If you do then it will help you in intellisense too. You can add something like this:

export interface SomeResponse {
  release_date: string;
  genre_relation: genre[]; // <----add it here
}

export interface genre {
  id: string;
  name: string;
}

Now in your template you can have a *ngFor iteration to iterate over the genre list:

<div *ngFor="let genre of api_response.genre_relation">
   <p>{{ genre.name }}</p>
</div>

CodePudding user response:

genre_relation is an array so it would be api_response.genre_relation[i].name where i is the index of your object

CodePudding user response:

Like in the other solutions, you can access the name using indexes.

<p *ngFor="let relation of api_response.genre_relation">
  {{ relation.name }}
</p>

Also you should change your interface like,

    export interface SomeResponse {
      release_date: string;
      genre_relation: { id: string, name: string }[];
    }
  • Related