Tom
Tom

Reputation: 87

Multiple v-for to get values from Nested JSON array in Vue.js

I am fetching data from external API and populating Table to display the JSON Data. The JSON data has multiple nested arrays, actually the data is for "Orders". So I am trying to get the Items of the order in a cell, for that I am using "v-if" but i could not archive this. The results I am getting for the below code is each item of the order in separate column, but i am trying to view the items in one cell and other 'meta_data'

Below is JSON data structure

"line_items": [{
    "name": "Salat",
    "meta_data": [{
        "id": 11500,
        "key": "size",
        "value": "full"
      },
      {
        "id": 1150001,
        "key": "Dressing",
        "value": "green"
      }
    ],
    "price": 4.28571399999999957941554384888149797916412353515625
  },
  {
    "name": "Chicken",
    "meta_data": [{
        "id": 115111112,
        "key": "size",
        "value": "Normal (7,00 €)"
      },
      {
        "id": 1151111113,
        "key": "Extra sauce",
        "value": "Bbq(0,50 €)"
      }
    ],
    "price": 7.14285700000000023379698177450336515903472900390625
  },
]

This is how I am creating the table

<table class="table table-bordered" id="table">
  <thead>
    <tr>
      <th scope="col">Order Id</th>
      <th scope="col">Name</th>
      <th scope="col">Items</th>
    </tr>
  </thead>
  <tbody>
    <tr 
      v-for="(order, index) in orders"
      :key="order.id"
      :class="{highlight: !order.is_printed}"
    >
      <td>{{ order.id }}</td>
      <td>{{ order.billing.first_name + " " +order.billing.last_name }}</td>
      <!-- <td>{{ order.line_items[].name}} </td>-->
      <td v-for="(items, index) in order.line_items">{{items.name}}</td>
    </tr>
  </tbody>
</table>

How can i archive this to get the names and meta data of the items of the order in one cell.

Suggestions will be great help.

Thank you

Upvotes: 0

Views: 1712

Answers (1)

76484
76484

Reputation: 9003

By having the v-for on the <td> element in the template it means you will have a <td> created for each item in your order.line_items array. To have all of these items render within a single <td> cell, you need to put the v-for inside the <td>. An unordered list (<ul>) may be an appropriate HTML element to use. For example:

<td>
    <ul>
        <li v-for="(items, index) in order.line_items">{{items.name}}</li>
    </ul>
</td>

I have created a fiddle for your reference.

Upvotes: 1

Related Questions