Rhys Edwards Rhys Edwards - 1 month ago 16
Jade Question

Iterate through nested array objects with Jade

I want to render this data on my view with Jade. This is returned from the QPX api. I have data structured like this.

{
kind: 'qpxExpress#tripsSearch',
trips: {
kind: 'qpxexpress#tripOptions',
requestId: 'OqaX52F0Z433IbMlh0PNr6',
data: {
kind: 'qpxexpress#data',
airport: [Object],
city: [Object],
aircraft: [Object],
tax: [Object],
carrier: [Object]
},
tripOption: [ [Object], [Object], [Object] ]
}
}


How do I access the nested object array in tripOption using Jade? I can't seem to work it out. This is my Jade template:

block content
.ui
for data in result
.ui_box
.ui_box__inner
.event
span #{data.tripOption[0].slice[0]}


This is the error I receive from Jade

Cannot read property '0' of undefined


Router

router.get('/', function(req, res, next) {
api.apiGet(function (data) {
console.log(data)
res.render('index', {result: data})
})
})

Answer

Your for loop is iterating on an object, which won't work. This isn't the usual for..in loop in native javascript

The code below modifies the router a little and passes the data (tripOptions) to the view in a more direct way. First the Jade template:

block content
  .ui
    for data in tripOptions
      .ui_box
        .ui_box__inner
          .event
            span #{data.someProp}

new router with the tripOption data made available to the view as tripOptions (plural):

router.get('/', function(req, res, next) {
  api.apiGet(function (data) {
    console.log(data) 
    res.render('index', {
      tripOptions: data.trips.tripOption
    })
  })
})