【问题标题】:Print out all objects with keys and values打印出所有带有键和值的对象
【发布时间】:2020-05-24 12:20:38
【问题描述】:

我正在做一个需要我打印出所有对象的项目,我必须使用嵌套 for in 循环。

结果应该是这样打印的:

team: Manchester United 
stadium:
   name:The Valley
   capacity:65000  
league: League 1
kit:
   home: blue and white
   away:light blue`

这是我想出的:

function footballClub() {
let club = {
    team: "Manchester United",
    stadium: {
        name: "The Valley",
        capacity: 65000
    },
    league: "League1",
    kit: {
        home: "blue and white",
        away: "light blue"
    }
}

    for (let outerKey in club) {
        for (let innerKey in club[outerKey]) {
            if (typeof club[outerKey === club.stadium.hasOwnProperty('name')]) {
                console.log(outerKey + ": " + innerKey + ": " + club[outerKey].name);
            }
            console.log(outerKey + ": " + club[outerKey]);
        }
    }
}

我被卡住了,因为它只是重复了球队、体育场等 8 次,因为外部和内部循环。

我似乎无法打印每个内部对象,因为它总是打印name,我尝试添加capacityhomeaway,但它从不打印它们,所以我必须删除它们来自代码。

有没有办法动态地打印所有外部对象和内部对象并且不重复 8 次?

【问题讨论】:

标签: javascript


【解决方案1】:

对代码稍作改动。在内部循环中导航之前,只需检查值是否为对象。当前代码中的问题是 for in 循环正在遍历字符串值。

function footballClub() {
  let club = {
    team: "Manchester United",
    stadium: {
      name: "The Valley",
      capacity: 65000
    },
    league: "League1",
    kit: {
      home: "blue and white",
      away: "light blue"
    }
  };

  for (let outerKey in club) {
    if (typeof club[outerKey] !== "string") {
      for (let innerKey in club[outerKey]) {
        console.log(
          outerKey + ": " + innerKey + ": " + club[outerKey][innerKey]
        );
      }
      console.log('');
    } else {
        console.log(outerKey + ": " + club[outerKey]);
        console.log('');
    }
  }
}

footballClub();

【讨论】:

    【解决方案2】:

    试试这个:

    const
      club = {
        team: 'Manchester United',
        stadium: {
          name: 'The Valley',
          capacity: 65000
        },
        league: 'League1',
        kit: {
          home: 'blue and white',
          away: 'light blue'
        }
      },
      result = Object.entries(club).map(([key, value]) =>
        key + ': ' + (typeof value === 'string' ?
          value :
          Object.entries(value).map(([innerKey, innerValue]) =>
            `\n\t${innerKey}: ${innerValue}`).join(''))
      ).join('\n');
      
    console.log(result)

    【讨论】:

      猜你喜欢
      • 2016-05-13
      • 2020-02-27
      • 2013-05-04
      • 2014-05-04
      • 2016-07-24
      • 2018-12-28
      • 2018-04-23
      • 2018-05-16
      • 1970-01-01
      相关资源
      最近更新 更多