如何从JSON文件中的嵌套数组中获取数据?

时间:2018-12-27 10:30:15

标签: arrays json fetch

我已经从JSON文件中获取了数据。但是当我尝试从中获取其他数据时,却无法做到,因为它是一个嵌套数组...我知道解决方案可以轻松实现,但这是第一个是时候尝试循环JSON文件..请提供您的输入。

SampleData = {
  "squadName": "Super hero squad",
  "homeTown": "Metro City",
  "formed": 2016,
  "secretBase": "Super tower",
  "active": true,
  "members": [
    {
      "name": "Molecule Man",
      "age": 29,
      "secretIdentity": "Dan Jukes",
      "powers": [
        "Immortality",
        "Turning tiny",
        "Radiation blast"
      ]
    },
    {
      "name": "Madame Uppercut",
      "age": 39,
      "secretIdentity": "Jane Wilson",
      "powers": [
        "Million tonne punch",
        "Damage resistance",
        "Superhuman reflexes"
      ]
    },
    {
      "name": "Eternal Flame",
      "age": 1000,
      "secretIdentity": "Unknown",
      "powers": [
        "Immortality",
        "Heat Immunity",
        "Inferno",
        "Teleportation",
        "Interdimensional travel"
      ]
    }
  ]
};

GetJsonData() {
    console.log(this.SampleData["powers"]);

    for (let i = 0; i < this.SampleData["powers"].length; i++) {   

      if (this.SampleData["powers"][i].Immortality) {

        console.log(this.SampleData.powers[i]);
      }
    }
  }

{name: "Molecule Man", age: 29, secretIdentity: "Dan Jukes", powers: Array(3)}
{name: "Eternal Flame", age: 1000, secretIdentity: "Unknown", powers: Array(3)}

1 个答案:

答案 0 :(得分:0)

您的代码需要遵循JSON数据的结构;特别是,这些都是您可以打印的有效内容:

console.log(this.SampleData.squadName);
console.log(this.SampleData.homeTown);
console.log(this.SampleData.members[0].name);
console.log(this.SampleData.members[0].powers[0]);

如果您想遍历每个成员并打印其信息,则可能看起来像这样:

this.SampleData.members.forEach(member => {
    let powerString = member.powers.join(', ');
    console.log('Name: ' + member.name);
    console.log('Age: ' + member.age);
    console.log('Powers: ' + powerString);
});

我使用了forEach,但是您也可以使用for (let i =循环。