Home > Blockchain >  Display elements from a JSON in Angular
Display elements from a JSON in Angular

Time:10-03

I have a file JSON here.

I will wish to display in BLOCAGES > BLOCAGE the following elements -> QTE & RAISON & DAT.

I would like to have a method perfect to display my elements. I want to avoid to use [0] in my method prepareDataForEtat(). Is it possible, please ?

prepareDataForEtat(response) {
        this.spinners.blockDetails = false;
        if (response['RETURNCODE'] == "OKK00") {

            let variable1 = response['BLOCAGES'];
        
            
            this.statusLine = {
                quantity: variable1 = response['BLOCAGES']['BLOCAGE'][0]['QTE'],
                raison: variable1 = response['BLOCAGES']['BLOCAGE'][0]['RAISON'],
                update: variable1 = response['BLOCAGES']['BLOCAGE'][0]['DAT']

            };

        }
    }

In Angular HTML, I have this:

...
<div class="row mb-4" *ngIf="blockDetails.length == 0">
<div class="col-12">
<div class="table-responsive">
<table class="table table-striped">
<tr style="background-color: #f8f9fa;">
   <td style="width: 13%;">Quantité</td>
   <td style="width: 13%;">Raison</td>
   <td style="width: 13%;">Date</td>
   <td style="width: 13%;">Référence</td>
</tr>
<tr  *ngIf="statusLine.quantity != 0" >
   <td>
      {{statusLine.quantity | number:'1.0-0' }}
   </td>
   <td>
      {{statusLine.raison  }}
   </td>
   <td>
      {{statusLine.update  }}
   </td>
  ...

CodePudding user response:

I assume you're trying to find the first "Blocage" (always).

There's no reason to try to avoid vanilla JS like array indexing but you should avoid the unnecessary duplication you have using the indexing.

Instead of doing variable1 = response['BLOCAGES']['BLOCAGE'][0]... multiple times, you could simply:

let variable1 = response['BLOCAGES']['BLOCAGE'][0];.

Then, just use it. (e.g. quantity: variable1['QTE'])

Or, if available, you could get the first element via deconstruction:

let [variable1] = response['BLOCAGES']['BLOCAGE'];

That'll grab the first element; then, just use it.

  • Related