[英]Having trouble displaying JSON
我已經仔細研究了為什么會發生這種情況。 我有一個腳本,它使用 AJAX 獲取本地 JSON 文件並將它們合並在一起,以便以后可以在 HTML 表中顯示數據。
該腳本可以很好地在 Chrome 控制台中顯示對象。 但我無法訪問特定元素,例如“object.country”。 關於如何解決這個問題的任何幫助?
控制台 output(縮短):
(3) [Array(244), "success", {…}]
0: Array(244)
[0 … 99]
0: {country: "Afghanistan", city: "Kabul", continent: "Asia", costline: 0, currency_name: "Afghanistan Afghani", …}
腳本
function onLoad() {
$.when(
$.ajax({
url: "./country-objects/country-by-capital-city.json",
type: "GET",
dataType: 'JSON'
}),
$.ajax({
url: "./country-objects/country-by-continent.json",
type: "GET",
dataType: 'JSON'
}),
$.ajax({
url: "./country-objects/country-by-costline.json",
type: "GET",
dataType: 'JSON'
}),
$.ajax({
url: "./country-objects/country-by-currency-name.json",
type: "GET",
dataType: 'JSON'
}),
$.ajax({
url: "./country-objects/country-by-flag.json",
type: "GET",
dataType: 'JSON'
}),
$.ajax({
url: "./country-objects/country-by-domain-tld.json",
type: "GET",
dataType: 'JSON'
})).then(function (res1, res2, res3, res4, res5, res6) {
const object = $.extend(true, res1, res2, res3, res4, res5, res6);
console.log(object);
})
}
- 編輯 -
每個 JSON 文件的示例對象(每個文件的第一個條目)。 以相同順序 az 的所有文件:
// /country-objects/country-by-capital-city.json
{
"country": "Afghanistan",
"city": "Kabul"
}
// /country-objects/country-by-continent.json
{
"country": "Afghanistan",
"continent": "Asia"
}
// /country-objects/country-by-costline.json
{
"country": "Afghanistan",
"costline": 0
}
// /country-objects/country-by-currency-name.json
{
"country": "Afghanistan",
"currency_name": "Afghanistan Afghani"
}
// /country-objects/country-by-flag.json
{
"country": "Afghanistan",
"flag_base64": "data:image\/svg+xml;base64,PHN2ZyB4bWxucz0ia......"
}
// /country-objects/country-by-domain-tld.json
{
"country": "Afghanistan",
"tld": ".af"
}
// Goal, continue for each country
{
"country": "Afghanistan",
"city": "Kabul",
"continent": "Asia",
"costline": 0,
"currency_name": "Afghanistan Afghani",
"flag_base64": "data:image\/svg+xml;base64,PHN2ZyB4bWxucz0ia......",
"tld": ".af"
},
我可以像這樣遍歷數組。
for (let i = 0; i < object.length; i++) {
let obj = object[i];
obj.forEach(function (item) {
console.log(item.country+" | "+item.continent);
});
}
感謝@Frenchy 指出這一點。
您可以迭代或過濾:
var data = [{ "country": "Afghanistan", "city": "Kabul", "continent": "Asia", "costline": 0, "currency_name": "Afghanistan Afghani", "flag_base64": "data:image\/svg+xml;base64,PHN2ZyB4bWxucz0ia......", "tld": ".af" }, { "country": "France", "city": "Paris", "continent": "Asia", "costline": 0, "currency_name": "Euro", "flag_base64": "data:image\/svg+xml;base64,PHN2ZyB4bWxucz0ia......", "tld": ".af" }, ]; //iterate data.forEach(function(rec, index){ console.log(rec.country, rec.city); }); var datafilter = data.filter( r => r.country == "France"); console.log(datafilter) datafilter = data.filter( r => r.costline == 0); console.log(datafilter)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.