Yelena TsK
Yelena TsK

Reputation: 21

Vue js get value from array

Have below code with flights info. Table shows price and flightDuration, but I fail to get airline name from flights array. I am new to Vue js, so would appreciate any help.

UPDATED (still not working):

    <tr v-for="flight in tickets.flights">
        <td>{{ flight.airline.name }}</td>
    </tr>

  JSON Data structure:
     data: {
    tickets: [{
  "price": 100,
  "flightDuration": "75",
  "flights": [
  {
    "departureTime": "12:00",
    "departureDate": "21 november",
    "arrivalTime": "13:15",
    "arrivalDate": "21 november",
    "airline": {
      "code": "DV",
      "name": "Scat"
    }
   }
   ]
  sortKey      : 'flights.departureDate',
            reverse      : false,
            columns      : [
                'flights.departureDate',
                'flightDuration'
            ]

https://jsfiddle.net/n7zjpgu5/

Upvotes: 2

Views: 1792

Answers (4)

dagalti
dagalti

Reputation: 1956

Below is the correct one and working.

<tr v-for="ticket in tickets">
<td  v-for="flight in ticket.flights">
      {{ flight.airline.name }}
</td>
</tr>

Codepen : https://codepen.io/anon/pen/mozPRW

<tr v-for="ticket in tickets">
 <td v-for="flight in ticket.flights">{{ flight.departureDate }}</td>
 <td v-for="flight in ticket.flights">{{ ticket.flightDuration }}</td>
 <td v-for="flight in ticket.flights">{{ flight.airline.name }}</td>
</tr>

Forked your Fiddle and code updated : https://jsfiddle.net/u2skLrz0/

Upvotes: 1

Hasibul-
Hasibul-

Reputation: 1412

The example will work for you.

<tr v-for = “flight in data.flights”>
    <td>{{flight.airline.name}}</td>
</tr>

Upvotes: 0

Luk&#225;š Irs&#225;k
Luk&#225;š Irs&#225;k

Reputation: 1132

You can access values from array like this:

<td>{{ product.flights[0].airline.name }}</td>

But if there are more elements in array only the first one will be shown. For that case you can iterate through array like this:

<tr v-for="product in list">
    <td>{{ product.price }}</td>
    <td>
      <span v-for="flight in product.flights">{{ flight.airline.name }}</span>
    </td>
</tr>

Upvotes: 0

Markus Madeja
Markus Madeja

Reputation: 856

Your problem is that flights is an array. That means there can be more than one airline. You will have to loop again over the flights.

v-for="flight in product.flights"

If you are sure that there will always be only one flight you can get your name by

{{ product.flights[0].airline.name }}

Upvotes: 1

Related Questions