简体   繁体   中英

angular render table ngFor for nested json with dynamic column names

Still learning Angular (version 8). I have the following JSON

{layer1 : [
     {
        id: 'lay1',
        name: 'first layer',
        results:
        [
           { rows: [{ col1: '0', description: 'any'}, {col1: '0b', description: 'meh'}] },
           { rows: [{ col1: '1', description: 'some'}] },
        ]
     }
  ]
, layer2: [
     {
        id: 'lay2',
        name: 'second layer'
        results:
        [
           { rows: [{ col1: '7', description: 'more'}] },
           { rows: [{ col1: '8', description: 'none'}] },
        ]
     }
  ]
}

The result should be a table like this

 <table id='lay1'>
   <tr>
     <td>0 </td>
     <td>any</td>
   </td>
   <tr>
     <td>0b </td>
     <td>meh</td>
   </td>
   <tr>
     <td>1</td>
     <td>some</td>
   </td>
 </table>
 <table id='lay2'>
   <tr>
     <td>7 </td>
     <td>more</td>
   </td>
   <tr>
     <td>8</td>
     <td>none</td>
   </td>
 </table>

note: results rows columns can change (sometimes 2 columns, sometimes 4 columns) and change the names (could be 'col1' but could be 'ident' or any other name). I have tried several options but I'm stuck on this. Any help highly appreciated

Try this -

<table *ngFor='let tableItem of data | keyvalue' [id]='tableItem?.value[0]?.id'>
  <tbody *ngFor='let rowsItem of tableItem?.value[0]?.results; let rowIndex = index'>
    <tr *ngFor='let rowItem of rowsItem?.rows; let rowIndex = index'>
      <td *ngFor='let colItem of rowItem | keyvalue; let colIndex = index'>
        {{colItem?.value}}
      </td>
    </tr>
  </tbody>
</table>

Working Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM