-1

How can I iterate over the Properties of an object and its childs objects? I used for in but I can't get the Songs info :/

let discos = [];

let disco1 = {
    discoName: 'name disco1',
    band: 'band name',
    code: 1,
    songs: [
        { 'songName': 'Song Name',
          'duration': 200,
       },
    ],
};
let disco2 = {
    discoName: 'name disco 2',
    band: 'band name 2',
    code: 1,
    songs: [
        { 'songName': 'Song Name 0',
          'duration': 200,
       },
    ],
};

discos.push(disco1,disco2);

for (let disco in discos){
    console.log(discos[disco].discoName);
}
Bel
  • 17
  • 2

1 Answers1

1

If you want a truly recursive solution, you will need to use a recursion, since this cannot be done using for.. in:

let discos = [];

let disco1 = {
    discoName: 'name disco1',
    band: 'band name',
    code: 1,
    songs: [
        { 'songName': 'Song Name',
          'duration': 200,
       },
    ],
};
let disco2 = {
    discoName: 'name disco 2',
    band: 'band name 2',
    code: 1,
    songs: [
        { 'songName': 'Song Name 0',
          'duration': 200,
       },
    ],
};

discos.push(disco1,disco2);

const visitRec = (obj, visitor) => {
  if (obj instanceof Array) {
    obj.forEach(e => visitRec(e, visitor));
  } else if (typeof obj == 'object') {
    for (let key in obj) {
      visitRec(obj[key], visitor);
    }
  } else {
    visitor(obj);
  }
}

visitRec(discos, console.log);

However, what I think you want is just:

for (let disco of discos){
  console.log(disco.discoName);
  for (let song of disco.songs) {
    console.log(song.songName);
  }
}
Christian Fritz
  • 18,961
  • 3
  • 42
  • 63