Vueer
Vueer

Reputation: 1500

Nested for loop will not work. Syntax?

Why this code does not work? The console.log in the second loop does not fire.

this.afDatabase.list(`data/users/${this.currentUserID}/visits/`, ref => ref.orderByChild('type').equalTo('study')).snapshotChanges().map(changes => {
  return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));})
  .take(1).subscribe(data => {


  let studys1 = [];
  let studys2 = [];

  for (let i=0; i < data.length; i++) {
    studys1.push(data[i]);

    for(let j=0; j < data[i].length; j++) {
      console.log(data[i][j]); //This not fires. I see nothing in the console
      studys2.push(data[i][j]) // Neither...
    }
  }

  console.log('Parent Length: ' + studys1.length); // Works
  console.log('Child Length: ' + studys2.length); //Always 0

});

The data I want to get:

enter image description here

console.log('%O',data) gives the following output:

Where the arrow shows is the nested object I need

Any idea?

Upvotes: 0

Views: 88

Answers (1)

Gabriel Barreto
Gabriel Barreto

Reputation: 6421

Iterating an object is different from iterating an array, your can use a for-in to iterate through objects:

for(var i in data){
  for(var j in data[i]){
    console.log(data[i][j]);
    studys2.push(data[i][j]);
  };
};

Hope this helps.

Upvotes: 1

Related Questions