【发布时间】:2016-12-30 23:20:04
【问题描述】:
我是 Angular 新手,我通过尝试使用 pokeapi 拉动每个 pokemon 的进化链来学习一点,但由于深度嵌套而遇到困难。
一个典型的响应对象是这样返回的:
{
"baby_trigger_item": null,
"id": 2,
"chain": {
"evolution_details": [],
"evolves_to": [
{
"evolution_details": [
{
"min_level": 16,
"min_beauty": null,
"time_of_day": "",
"gender": null,
"relative_physical_stats": null,
"needs_overworld_rain": false,
"turn_upside_down": false,
"item": null,
"trigger": {
"url": "http://pokeapi.co/api/v2/evolution-trigger/1/",
"name": "level-up"
},
"known_move_type": null,
"min_affection": null,
"party_type": null,
"trade_species": null,
"party_species": null,
"min_happiness": null,
"held_item": null,
"known_move": null,
"location": null
}
],
"evolves_to": [
{
"evolution_details": [
{
"min_level": 36,
"min_beauty": null,
"time_of_day": "",
"gender": null,
"relative_physical_stats": null,
"needs_overworld_rain": false,
"turn_upside_down": false,
"item": null,
"trigger": {
"url": "http://pokeapi.co/api/v2/evolution-trigger/1/",
"name": "level-up"
},
"known_move_type": null,
"min_affection": null,
"party_type": null,
"trade_species": null,
"party_species": null,
"min_happiness": null,
"held_item": null,
"known_move": null,
"location": null
}
],
"evolves_to": [],
"is_baby": false,
"species": {
"url": "http://pokeapi.co/api/v2/pokemon-species/6/",
"name": "charizard"
}
}
],
"is_baby": false,
"species": {
"url": "http://pokeapi.co/api/v2/pokemon-species/5/",
"name": "charmeleon"
}
}
],
"is_baby": false,
"species": {
"url": "http://pokeapi.co/api/v2/pokemon-species/4/",
"name": "charmander"
}
}
}
我必须进入evolves_to 属性,并获取species.name 以及evolution_details.min_level 和evolution_details.trigger.name,以及evolution_details.item(如果不为空)
但是正如你所看到的,evolves_to 属性本身包含另一个嵌套在其中的evolves_to,其中又嵌套了另一个
这是我悲伤的尝试(在 http.get 之后),我现在卡住了。
var evoObject = response.data;
function loopEvo(obj){
angular.forEach(obj, function(value, key, object){
if (key == 'evolves_to' && value != []) {
//from here I can get top level data, but...
}
});
}
loopEvo(evoObject.chain);
我不知道如何递归地深入研究对象并不断获取数据,有人可以提供任何帮助吗?我很乐意将此作为一个很好的学习机会来遍历复杂的 json 对象。
【问题讨论】:
标签: javascript angularjs