[英]jQuery loop through JSON objects
我想遍歷此JSON文件(下面的結構),並獲取所有國家(例如,奧地利)的酒店。 使用getJson()
無法更改JSON文件中的任何內容。
任何幫助將不勝感激。
[
{
"Site ID": 19955,
"Hotels": "Ramada Salzburg City Centre",
"Stadt": "Salzburg",
"Country": "Austria",
"Region": "Central & Eastern Europe",
"Link DE": "",
"Link EN": "",
"Link TR": "",
"Lat": 47.8137521,
"Long": 13.044259,
"Image": "/Salzburg.jpg"
}, {
"Site ID": 1211,
"Hotels": "test",
"Stadt": "Salzburg",
"Country": "NZ",
"Region": "Central & Eastern Europe",
"Link DE": "",
"Link EN": "",
"Link TR": "",
"Lat": 47.8137521,
"Long": 13.044259,
"Image": "/Salzburg.jpg"
}
]
我不知道您到底想做什么,但這是一個工作示例,該示例循環json並檢查酒店是否在奧地利,並將名稱和城市登錄到控制台:
var json = [{
"Site ID": 19955,
"Hotels": "Ramada Salzburg City Centre",
"Stadt": "Salzburg",
"Country": "Austria",
"Region": "Central & Eastern Europe",
"Link DE": "",
"Link EN": "",
"Link TR": "",
"Lat": 47.8137521,
"Long": 13.044259,
"Image": "/Salzburg.jpg"
}, {
"Site ID": 1211,
"Hotels": "test",
"Stadt": "Salzburg",
"Country": "NZ",
"Region": "Central & Eastern Europe",
"Link DE": "",
"Link EN": "",
"Link TR": "",
"Lat": 47.8137521,
"Long": 13.044259,
"Image": "/Salzburg.jpg"
}];
$(json).each(function () {
if (this.Country === "Austria") {
console.log("Found hotel " + this.Hotels + " in " + this.Stadt);
}
});
var json = [{ "Site ID": 19955, "Hotels": "Ramada Salzburg City Centre", "Stadt": "Salzburg", "Country": "Austria", "Region": "Central & Eastern Europe", "Link DE": "", "Link EN": "", "Link TR": "", "Lat": 47.8137521, "Long": 13.044259, "Image": "/Salzburg.jpg" }, { "Site ID": 1211, "Hotels": "test", "Stadt": "Salzburg", "Country": "NZ", "Region": "Central & Eastern Europe", "Link DE": "", "Link EN": "", "Link TR": "", "Lat": 47.8137521, "Long": 13.044259, "Image": "/Salzburg.jpg" }]; var austriaHotels = json.filter(function(item) { return item.Country == 'Austria'; }); var hotelsName = austriaHotels.map(function(item) { return item.Hotels; }); console.log(hotelsName);
您需要存儲位置,在這些位置上循環,然后將匹配的位置分組到一個新的數組中。
var locations = [{
"Site ID": 19955,
"Hotels": "Ramada Salzburg City Centre",
"Stadt": "Salzburg",
"Country": "Austria",
"Region": "Central & Eastern Europe",
"Link DE": "",
"Link EN": "",
"Link TR": "",
"Lat": 47.8137521,
"Long": 13.044259,
"Image": "/Salzburg.jpg"
}, {
"Site ID": 1211,
"Hotels": "test",
"Stadt": "Salzburg",
"Country": "NZ",
"Region": "Central & Eastern Europe",
"Link DE": "",
"Link EN": "",
"Link TR": "",
"Lat": 47.8137521,
"Long": 13.044259,
"Image": "/Salzburg.jpg"
}];
// Store the matched hotels here
var matches = [];
// Loop over hotels
for( i=0; i<locations.length; i++ ) {
// Check if the location is in Austria, if so push it to our matches array
if( locations[i].Country == 'Austria' ) {
matches.push(locations[i]);
}
}
// Check for matched hotels
console.log( matches );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.