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

3
  • can you provide the array data? Commented Jun 8, 2017 at 9: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 for arrays. Commented Jun 8, 2017 at 9:53
  • news is not an array, news.leaving.all is. Question is a simple matter of typo, unlikely to be useful to future visitors Commented Jun 8, 2017 at 9:53

4 Answers 4

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++) {                
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @ykay … I tried that earlier but it didn't work either…
probably because yo uare looking at new.length which should also be switched
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>';
}

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.