Filip Blaauw
Filip Blaauw

Reputation: 761

V-for inside v-for in Vue.js

I'm trying to get object items from inside a parent object using a v-for inside another v-for in Vue.js.

Data structure:

flights: [
  {
    "airline": "BA",
    "airport": "EBJ",
    "status": {
      "_code": "A",
      "_time": "2018-03-02T14:19:00Z"
    }
  },
  etc....
]

<div v-for="flight in flights">
  <p>{{flight.airline}}</p>
  <p>{{flight.airport}}</p>

  <div v-for="st in flight.status">
    <p>{{st._code}}</p> // should return 'A'
    <p>{{st._time}}</p> // should return '2018-03-02T14:19:00Z'
  </div>
</div>

However, neither st._code or st._time return anything. st returns both values ("A" and "2018-03-02T14:19:00Z").

Any idea on how to return the single values inside the status object?

Upvotes: 0

Views: 3104

Answers (2)

Daniel Beck
Daniel Beck

Reputation: 21514

It is possible to use v-for on an object, as you're trying to do with status, but the syntax is slightly different; in cases where iterating over an object is useful you'll generally want to include the key as well as the value:

<div v-for="(val, key) in flight.status">
  <p>{{key}}: {{val}}</p>
</div>

would output

<p>_code: A</p>
<p>_time: 2018-03-02T14:19:00Z</p>

In your case you already know the specific keys you want, so it would be easier to not use v-for and instead just use e.g {{flight.status._code}}.

Unless there can be more than one "status" per flight, there's no good reason to wrap status in an array. This will work with your existing data structure:

<div v-for="flight in flights">
  <p>{{flight.airline}}</p>
  <p>{{flight.airport}}</p>
  <p>{{flight.status._code}}</p> 
  <p>{{flight.status._time}}</p> 
</div>

Upvotes: 1

samayo
samayo

Reputation: 16495

The reason you are not seeing the expected output is because, of this line:

<div v-for="st in flight.status"> 

That means you are expecting vue to iterated throught this:

"status": {
  "_code": "A",
  "_time": "2018-03-02T14:19:00Z"
}

and the above is an object, not an array ... so unless status is an array, it won't work.

If you expect your code to work, try changing your array to this:

  flights: [
    {
      "airline": "BA",
      "airport": "EBJ",
      status: [{
        "_code": "A",
        "_time" : "2018-03-02T14:19:00Z"
      }]
    }
  ]

working demo:

https://jsfiddle.net/943bx5px/82/

Upvotes: 0

Related Questions