Home > Mobile >  How to loop multiple objects in <td> in Vue.js?
How to loop multiple objects in <td> in Vue.js?

Time:02-14

I have an Array with multiple Objects, now I want to loop each object as a <tr> in a <table>. I have done that.

However, these objects may contain multiple objects. Then I want to display all objects within 1 object in 1 <td>.

So this is the code what I have currently:

<tr v-for="(data, index) in tableData" :key="index">
  <td
    v-for="(propertyValue, property, propertyIndex) in data.rowData"
    :key="property"
    
  >
    <div >
      <span>{{ propertyValue }}</span>
    </div>
  </td>
</tr>
const tableData = [
  {
    rowData: {
      name: 'test',
      description: 'test',
      datatype: 'string',
    },
    rowComponent: {
      test: 'testComponent',
    },
  },
  {
    rowData: {
      name: 'test 1',
      description: 'test 1',
      datatype: 'string',
    },
  },
  {
    rowData: {
      name: 'test 2',
      description: 'test 2',
      datatype: 'link',
    },
  },
];

This looks like this in the front-end: table example

As you can see 1st object in the tableData contains 2 objects (rowData and rowComponent). now I want to display the 2nd object (rowComponent) also in the same <td> as the first object (rowData).

This is what I want:

example of what I want

This should also happen for the other td's when there are multiple properties in the 2nd object.

How can I do this?

CodePudding user response:

<tr v-for="(data, index) in tableData" :key="index">
  <td
    v-for="(myData, index) in data"
    :key="index"
    
  >
    <div >
      <span
        v-if="myData.rowData"
        v-for="(propertyValue, property, propertyIndex) in myData.rowData"
        :key="property"
      >{{ propertyValue }}</span>
      <span
        v-if="myData.rowComponent"
        v-for="(propertyValue, property, propertyIndex) in myData.rowComponent"
        :key="property"
      >{{ propertyValue }}</span>
    </div>
  </td>
</tr>

CodePudding user response:

Option 1: Calculate rowComponent per iteration

This can be done with a function that calculates the rowComponent for a particular column:

const getRowComponent = ({ rowComponent }, index) =>
  // Only proceed if rowComponent exists
  rowComponent &&

  // Get the object values of rowComponent as an array
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
  Object.values(rowComponent)

  // Get array element at specified index (undefined if not found)
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at
  .at(index)

The function would be used in the template per item of tableData, using the rowData index (named propertyIndex in this case):

<tr v-for="(data, index) in tableData" :key="index">
  <td v-for="(propertyValue, property, propertyIndex) in data.rowData" :key="property" >
    <div >
      <span>{{ propertyValue }}</span>
                                 
  • Related