0

I know iteration has been covered before - I'm usually pretty ok with it but struggling this time.

I have the following information I'm trying to loop through:

Object { leaving: object { all: array[10] } }

I can quite easily return a single result by returning:

 var html = '<p>' + news.leaving.all[0].departure_time + '</p>';

But when I try to loop:

    var html = "";
    var i;
    for (i = 0; i < news.length; i++) {                
        html +=
        '<p>' + news[i].leaving.all.departure_time '</p>';
     }

I get nothing…

Any help with this will be great.

Thanks

  • can you provide the array data? – Arun AK Jun 08 '17 at 09:51
  • Is `news` the Object you wrote at the top? What is its length property? (Clue: it looks to me like it doesn't have one.) Also you should consider using [forEach](https://stackoverflow.com/a/10167931/5920499) for arrays. – daphtdazz Jun 08 '17 at 09:53
  • news is not an array, news.leaving.all is. Question is a simple matter of typo, unlikely to be useful to future visitors – Alex Jun 08 '17 at 09:53

4 Answers4

3

It looks like you need

'<p>' + news.leaving.all[i].departure_time '</p>';

rather than

 '<p>' + news[i].leaving.all.departure_time '</p>';

and change also

for (i = 0; i < news.length; i++) {                

to

for (i = 0; i < news.leaving.all.length; i++) {                
2

You also have to iterate over the "all" member:

var html = "";
for (var i = 0; i < news.leaving.all.length; j++) {                
   html +=
   '<p>' + news.leaving.all[i].departure_time '</p>';
}
Eytibi
  • 545
  • 6
  • 12
1

You can use Array.prototype.forEach() to iterate over the array news.leaving.all.

Code example:

var news = {leaving: {all: [{departure_time: '01:00'},{departure_time: '02:00'},{departure_time: '03:00'}]}},
    html = "";
    
news.leaving.all.forEach(function (n) {
  html += '<p>' + n.departure_time + '</p>';
});

console.log(html);
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
0

You have to loop over news.leaving.all:

// Let's say this is our data
var news = {
  leaving: {
    all: [{
      departure_time: '01:00'
    },
    {
      departure_time: '02:00'
    },
    {
      departure_time: '02:00'
    }]
  }
};

var html = "";
var i;
for (i = 0; i < news.leaving.all.length; i++) {                
  html += '<p>' + news.leaving.all[i].departure_time + '</p>';
 }
     
console.log(html);     
PeterMader
  • 6,987
  • 1
  • 21
  • 31