Home > Blockchain >  How do i iterate an array of json data to always get the first json object
How do i iterate an array of json data to always get the first json object

Time:11-10

I'm trying to get the first json object from the video array , I only want to get full highlights and not the goals

{
"response": [
    {
    title: "United vd Chelsea",
  "videos": [
            {
                "title": "Highlights",
                "embed": "<div>Full highlight video is embed here</div>"
            },
            {
                "title": "goal 1",
                "embed": "<div>goal is embed here</div>"
            },
            {
                 "title":"goal 2",
                "embed": "<div>goal is embed here</div>"
           }]
        },
    {
    title: "Arsenal vs Lfc",
  "videos": [
            {
                "title": "Highlights",
                "embed": "<div>Full highlight video is embed here</div>"
            },
            {
                "title": "goal 1",
                "embed": "<div>goal is embed here</div>"
            },
            {
                 "title":"goal 2",
                "embed": "<div>goal is embed here</div>"
           }]
        } ....}

Here is my component.html , this returns full highlights and goals videos. I only want full highlight videos

<div  *ngFor="let results of data.response.slice(0,6)">
             <div class="panel panel-default">
                <div *ngFor="let result of results.videos">
                    <p [innerHTML]="result.embed | safe">  </p>
                    <p>{{result.title}}</p> 
                </div>

Can anyone help please

CodePudding user response:

Solution 1

Extract first item with title: Highlight from results.videos with slice.

Assumption: 'Highlight' element will be in the first element of the results.videos array.

<div *ngFor="let result of results.videos.slice(0, 1)">
  <p [innerHTML]="result.embed"></p>
  <p>{{ result.title }}</p>
</div>

Sample Solution 1 on StackBlitz


Solution 2 (Preferred)

More preferred this solution. With *ngIf to display HTML element only when result.title == 'Highlights'.

<div *ngFor="let result of results.videos">
  <ng-container *ngIf="result.title == 'Highlights'">
    <p [innerHTML]="result.embed"></p>
    <p>{{ result.title }}</p>
  </ng-container>
</div>

Sample Solution 2 on StackBlitz

  • Related