javascript - 使用 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;
解决方案
第一步,找到英文条目
第 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");
}
推荐阅读
- react-native - 如何在反应导航中更改抽屉导航中的背景颜色
- python - 无法将文件夹中的所有 TXT 转换为 CSV 文件
- python-3.x - pyinstaller 可执行文件失败
- android - 应用程序崩溃,空指针异常。列表视图给出空异常
- javascript - 如果没有发送任何内容,为什么当浏览器关闭时服务器上的我的 php SSE 文件继续工作?
- database - 不能在 DolphinDB 的函数定义中声明 share 语句
- mysql - 如何从多个选择查询中获取临时表中一行的列/字段数据?
- c# - 与已发布的已安装应用程序相比,代码的调试版本运行速度快 10 倍
- spring - 在 Spring 中使用 Thymeleaf 绑定列表。错误:对象验证失败
- javascript - 这行代码“var app = express()”是如何工作的?