javascript - 匹配 JSON 对象中的键/值
问题描述
我有一个学校项目,我们正在学习 JSON。我要做的是弄清楚如何将键与另一个对象属性中存在的其他键匹配。
我正在使用旧的 api 来提取 nfl 播放器信息。以下是提取数据的 url 示例:
http://api.fantasy.nfl.com/v1/players/stats?statType=seasonStats&season=2018&week=16&format=json
我正在使用 AJAX 调用数据并将结果字符串化到一个表中。
$.ajax({
url: queryURL,
method: "GET"
}).then(function(response) {
var tbl = $("<table>");
$(tbl).addClass("table");
var objCount = JSON.stringify(response.players.length);
$(tbl).append("<thead><tr><th>ID</th><th>Team</th><th>POS</th>
<th>Player</th><th>Stat</th></tr></thead><tbody>");
for (p = 1; p < 2; p++) {
var id = response.players[p].id;
var team = response.players[p].teamAbbr;
var pos = response.players[p].position;
var plyr = response.players[p].name;
var stat = JSON.stringify(response.players[p].stats);
var plyrStatsObjLen =
JSON.stringify(response.players[p].stats.length);
console.log("statObjLength: " + plyrStatsObjLen);
$.each(response.players[p].stats, function(key, value) {
console.log(key + ": " + value);
});
$(tbl).append("<tr><td>" + id + "</td><td>" + team + "</td><td>" + pos + "</td><td>" + plyr + "</td><td>" + stat + "</td>");
}
$(tbl).append("</tbody><br/><br/>");
$("#statOutput").append(tbl);
});
这是我正在做的事情: https ://jsfiddle.net/kenneth2k1/kcf5duLr/
如果您注意到结果,我将 stats 属性分离到它自己的列中,但它仍然在对象的键/值结构中。
现在,这是另一个包含每个统计信息的网址: https ://api.fantasy.nfl.com/v1/game/stats?format=json
"stats": [
{
"id": 1,
"abbr": "GP",
"name": "Games Played",
"shortName": "GP"
},
{
"id": 2,
"abbr": "Att",
"name": "Passing Attempts",
"shortName": "Pass Att"
},
{
"id": 3,
"abbr": "Comp",
"name": "Passing Completions",
"shortName": "Pass Comp"
}, ... and so on
因此,例如键 ID“1”对应于 stat 引用对象中的“Games Played”。
我对这一切都很陌生,所以我无法理解的是,如果我想用来自 stats 引用对象的相应名称值替换输出中的键,我该怎么做?
例如来自 jsfiddle 输出,而不是
{"1":"9","13":"1"}
它会说
Games Played: 9, Rushing Attempts: 1
我希望这是有道理的。基本上我想学习如何将一个 JSON 对象中的键与另一个对象中的键值匹配。
非常感谢您的帮助。
解决方案
您可以将第二个 AJAX 调用嵌套在第一个调用的成功函数中,然后将变量分配和表创建放入第二个成功函数中。在第二个成功函数中,您将使用简单的for
循环将玩家数据中的每个数字统计信息与统计数据中的正确名称进行匹配,如下所示:
$(document).ready(function () {
var statType = "seasonStats";
var season = "2018";
var week = "15";
var playersURL = "https://api.fantasy.nfl.com/v1/players/stats?format=json" + "&statType=" + statType + "&season=" + season + "&week=" + week;
var statURL = "https://api.fantasy.nfl.com/v1/game/stats?format=json";
// Now we get the stats
$.ajax({
url: statURL,
method: "GET",
success: function (response) {
const stats = response.stats;
// Then we get the players
$.ajax({
url: playersURL,
method: "GET",
success: function (response) {
const players = response.players;
// Now we do the rest of the logic
// Here's our table creation and header
var tbl = $("<table>");
$(tbl).addClass("table");
$(tbl).append("<thead><tr><th>ID</th><th>Team</th><th>POS</th><th>Player</th><th>Stat</th></tr></thead><tbody>");
// Here's where we create variables for each individual player
for (p = 0; p < 1; p++) {
let id = players[p].id;
let team = players[p].teamAbbr;
let pos = players[p].position;
let plyr = players[p].name;
// We create an empty object to hold the named statistics we're about to find
let statistics = {};
// Now we'll loop over the players and statistics to get names for all the stats
playerStats = players[p].stats;
for (playerStat in playerStats) {
for (s = 0; s < stats.length; s++) {
// if the player's statistic matches the id of the property from the stats object, we add that stat name and its total for that player as a property of the object we created above
if (playerStat === JSON.stringify(stats[s].id)) {
let statName = stats[s].name;
let statCount = playerStats[playerStat];
statistics[statName] = statCount;
}
}
};
// Now we turn our statistics object into text that can actually go into our table
let prettyStats = "";
for (statistic in statistics) {
prettyStats = prettyStats + `${statistic}: ${statistics[statistic]}
`
}
// Now that we have data for the player, we add a row to our table
$(tbl).append("<tr><td>" + id + "</td><td>" + team + "</td><td>" + pos + "</td><td>" + plyr + "</td><td>" + prettyStats + "</td>");
}
//Here's the bottom of our table and its creation inside the div
$(tbl).append("</tbody><br/><br/>");
$("#statOutput").append(tbl);
}
});
}
});
});
您可能希望对 的输出进行进一步的文本格式化prettyStats
,但它会为您提供您正在寻找的数据。
推荐阅读
- r - 每个人具有多个/堆叠变量的热图
- xquery - XQuery - 输出一系列带有分隔符的 HTML 元素
- javascript - 链接到 Play 商店 - 智能应用横幅 - Android
- typescript - 如何在 Jest 中模拟一个函数
- php - 如何将 URL 字符串放入 json Viber API php
- maven - FindBugs 插件的 SonarQube 问题
- c# - 从 C++ 原生插件更新 Vector3 数组
- javascript - 根据下拉列表 MVC 中的选择重新加载页面
- cuda - NvLink 或 PCIe,如何指定互连?
- maven - Jenkins:无法通过 Jenkins 运行本地 Maven 项目