首页 > 解决方案 > 使用 jQuery 和 PokéAPI 查找 JSON 密钥匹配

问题描述

我正在尝试在我正在开发的应用程序中使用 PokéAPI 查找并使用语言 JSON 端点的英文翻译。在提交对下面显示的 URL 之一的调用时,我需要使用翻译。不幸的是,英语语言键在数组响应中的顺序并不总是相同,所以我需要一种查找和检查它的方法,以便在前端显示正确的英语翻译。

我试图检索: flavor_text_entries[X].language.en在每个搜索中键入并检索flavor_text_entries[X].flavor_text以在前端显示描述。

API 网址 1:

https://pokeapi.co/api/v2/pokemon-species/3/

API 网址 2:

https://pokeapi.co/api/v2/pokemon-species/10/

代码:

var pokeBio = $("[data-poke-bio]").html();

function submit(){

 var pokeID = $("[data-poke-id]").val();
 var pokeSpecURL = "https://pokeapi.co/api/v2/pokemon-species/" + pokeID;

 $.ajax({
    type: "GET",
    url: pokeSpecURL,
    success: function(dataSpec){ 
      ajaxSpecSuccess(dataSpec);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      ajaxError();
    }
  });
}

function ajaxSpecSuccess(dataSpec){
  var pokeMatchBio = dataSpec.flavor_text_entries[1].flavor_text;
  var pokeBio = $("[data-poke-bio]").html(pokeMatchBio);
}

我需要操纵的片段:

var pokeMatchBio = dataSpec.flavor_text_entries[1].flavor_text;

标签: javascriptjqueryjsonajax

解决方案


第一步,找到英文条目

第 2 步,显示它的 flavor_text 或一条消息(如果没有找到)

let englishEntry = dataSpec.flavor_text_entries.find(entry => entry.language && entry.language.name && entry.language.name === 'en');

if (englishEntry) {
  console.log(englishEntry.flavor_text);
} else {
  console.log("English entry not found");
}

推荐阅读