使用循环遍历对象中的数组

时间:2018-02-13 07:09:47

标签: javascript arrays json

我在一个对象中有几个不同的数组。我想用数字值来使用它们,因为我需要将它们设置成循环到手风琴中的不同插槽。 Json文件我得到的值看起来有点像这样(例如口袋妖怪):

{
  "Pokemon": {
    "FirePokemon": [
      {
        "name": "Vulpix",
        "speed": "10",
        "attack": "10",
        "defence": "10"
      },
      {
        "name": "Charmander",
        "speed": "10",
        "attack": "10",
        "defence": "10"
      }
    ],
    "WaterPokemon": [
      {
        "name": "Squirtle",
        "speed": "10",
        "attack": "10",
        "defence": "10"
      },
      {
        "name": "Wartortle",
        "speed": "10",
        "attack": "10",
        "defence": "10"
      }
    ],
    "GrassPokemon": [
      {
        "name": "Bulbasaur",
        "speed": "10",
        "attack": "10",
        "defence": "10"
      },
      {
        "name": "Oddish",
        "speed": "10",
        "attack": "10",
        "defence": "10"
      }
    ]
  }
}

我想将数据称为:

function SetJsonDataToAccordion() {
    for (var i = 0; i < Object.keys(pokemondata).length; i++) {
        CreateAccordionContent(pokemondata[i], ".accordtitle"+i);
    }
}

pokemondata是获取所有Json数据的变量。当然pokemondata [i]不起作用,但我想循环口袋妖怪类型,比如在循环中交换火然后浇水然后草等,而不调用数组名称。如果我只是将它设置为pokemondata.FirePokemon但我需要循环它们,这一切都有效。那么有没有办法可以循环通过对象中的数组?

2 个答案:

答案 0 :(得分:1)

您可以使用for / in循环。

根据您的示例:您需要3个嵌套循环。

var obj = {
  "Pokemon": {
    "FirePokemon": [{
        "name": "Vulpix",
        "speed": "10",
        "attack": "10",
        "defence": "10"
      },
      {
        "name": "Charmander",
        "speed": "10",
        "attack": "10",
        "defence": "10"
      }
    ],
    "WaterPokemon": [{
        "name": "Squirtle",
        "speed": "10",
        "attack": "10",
        "defence": "10"
      },
      {
        "name": "Wartortle",
        "speed": "10",
        "attack": "10",
        "defence": "10"
      }
    ],
    "GrassPokemon": [{
        "name": "Bulbasaur",
        "speed": "10",
        "attack": "10",
        "defence": "10"
      },
      {
        "name": "Oddish",
        "speed": "10",
        "attack": "10",
        "defence": "10"
      }
    ]
  }
};

for (var key1 in obj.Pokemon) {
  console.log("=======================");
  console.log(key1);
  console.log("=======================");

  for (var key2 in obj.Pokemon[key1]) {
    for (var key3 in obj.Pokemon[key1][key2]) {
      console.log(key3 + ": " + obj.Pokemon[key1][key2][key3]);
    }
    console.log("****");
  }
}

答案 1 :(得分:0)

迭代两者。使用Object.keys,您可以获得口袋妖怪类型的列表,并且可以使用该信息迭代每个口袋妖怪。

var pokemonData = obj.Pokemon;
Object.keys(pokemonData).forEach(type => {
   // do something with pokemon type
   pokemonData[type].forEach(pokemon => {
      //do something with actual pokomen
   });
});