Restructure a objects array for table

Viewed 57

I have a table header:

      fields: [
        'description',
        'potSize',
        'price',
      ],

I have my table data:

      testArray: [
        {
          price: '10,00',
          potSize: 'C2',
          description: 'desc',
        },
        {
          price: '10,00',
          potSize: 'C2',
          description: 'rwefv ',
        },
        {
          price: '10,00',
          potSize: 'C2',
          description: '',
        },
      ],

Both are read in a table component

    <thead>
      <tr>
        <th v-for="item in fields" :key="item">{{ item }}</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(item, key) in testArray" :key="key">
        <td v-for="(keys, col) in item" :key="keys">
          {{ item[col] }}
        </td>
      </tr>
    </tbody>

As you can see is the header row and the data row a key mismatch. I need to display the testArray key-value pairs in the headers order. How can I go most effective about that?

Expected output: enter image description here

1 Answers

In the inner loop, loop through fields instead of item and then look up corresponding field by key:

  <tr v-for="(item, key) in testArray" :key="key">
    <td v-for="col in fields" :key="col">
      {{ item[col] }}
    </td>
  </tr>
Related