Rhys Edwards Rhys Edwards - 1 month ago 8
JSON Question

For Loop: TypeError: Cannot read property '0' of undefined

I am trying to loop through some data returned returned from an API request which is structured as below:

[ { kind: 'qpxexpress#tripOption',
saleTotal: 'USD107.70',
id: 'fANabOjuLoDMb9zppwbeXL002',
slice: [ [Object] ],
pricing: [ [Object] ] },
{ kind: 'qpxexpress#tripOption',
saleTotal: 'USD107.70',
id: 'fANabOjuLoDMb9zppwbeXL003',
slice: [ [Object] ],
pricing: [ [Object] ] },
{ kind: 'qpxexpress#tripOption',
saleTotal: 'USD107.70',
id: 'fANabOjuLoDMb9zppwbeXL001',
slice: [ [Object] ],
pricing: [ [Object] ] } ]


However my for loop is giving me a type error which I'm struggling to debug. What am I missing?

request(options)
.then(function (response) {
//.log(response.trips.tripOption)
let selects = 0
for(let i = 0; i < response.trips.tripOption.length; i++) {
if (response.trips.tripOption[i].selected) {
selects++
}
}
return selects
console.log('hello' + ' ' + selects)

})
.catch(function (err) {
console.log(err)
})

Answer

You got a typo in Line 6 in your snippet, writing tripOptions not tripOption.

Also, should console.log() before you return selects.

Comments