简体   繁体   中英

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})
  })
})

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
    })
  })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM