【问题标题】:Iterate over the Properties of an object and its childs objects [duplicate]迭代对象及其子对象的属性[重复]
【发布时间】:2021-12-04 22:31:29
【问题描述】:

如何迭代对象及其子对象的属性?我用过 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);

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

【问题讨论】:

  • discos 是一个数组,因此您应该使用 for .. of 而不是 for .. in 进行迭代
  • 此信息:歌曲:[ { 'songName': 'Song Name', 'duration': 200, }, ],

标签: javascript arrays loops


【解决方案1】:

如果您想要一个真正的递归解决方案,则需要使用递归,因为使用 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);

但是,我认为你想要的只是:

for (let disco of discos){
  console.log(disco.discoName);
  for (let song of disco.songs) {
    console.log(song.songName);
  }
}

【讨论】:

    猜你喜欢
    • 2016-02-26
    • 2011-06-18
    • 2012-07-23
    • 2012-02-14
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    相关资源
    最近更新 更多