0

I have this for (var i = 0; i < podcasts.episodes.showOne.length; i++).

It works because the show called showOne is present. It is the first show, so it has the index 0.

There is a second show, let's call it showTwo, at index 1.

Ideally I'm looking for something like (var i = 0; i < podcasts.episodes.[0].length; i++), but that doesn't work. Is there a way to do this?

While we are at it, can I replace "showOne" with a variable too, where the variable represents the show name? That is, how can I insert a variable into here podcasts.episodes.VARIABLE.length?

Cheers!

user1525
  • 157
  • 7
  • *"It is the first show, so it has the index 0"* - Except...no it doesn't. If you're accessing it byname then `podcasts.episodes` is an object, right? Object properties don't really have indices. You can, however, loop through those properties without knowing their names in advance, as shown in one of the answers below, except if they have names like `"showOne"` you can't count on them being in the order you might want. The last part of your question has [already been asked](http://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) (repeatedly). – nnnnnn May 03 '17 at 03:30

2 Answers2

0

You didn't share your object, but here is one possible solution:

var obj = {
  a : [
    [1, 2],
    [3, 4, 5]
  ]
};

var len = obj.a[0].length;
for(var i = 0; i < len; i++)
  console.log(obj.a[0][i]); // 1, 2

len = obj.a[1].length;
for(var i = 0; i < len; i++)
  console.log(obj.a[1][i]); // 3, 4, 5
Mehdi Dehghani
  • 10,970
  • 6
  • 59
  • 64
0

Try using Object.keys(podcasts.episodes). It will give you an array of all of the episode names. You can then loop through each one:

// episodeNames is an array of all the episodes
let episodeNames = Object.keys(podcasts.episodes)

for(var i = 0; i < episodeNames.length; i++) {
    // this will iterate through each episode

    for(var j = 0; j < episodeNames[i].length; j++) {
         // this will iterate through all the items in each episode 
    }
}
EJ Mason
  • 2,000
  • 15
  • 15