![](/img/trans.png)
[英]How do I get specific value key pair in ajax javascript for datatype json?
[英]How do I search for a specific JSON key value pair using Javascript?
我目前正在構建一個應用程序,該應用程序可以告訴您指定城市中即將發生的事件的天氣。我使用了兩個API,一個返回的對象數組對應於插入文本輸入中的藝術家的每個事件,另一個返回輸入另一個輸入的城市的天氣。
我正在使用.getJSON方法來檢索數據。 當前,藝術家API返回所有輸入的藝術家即將發生的事件,並且我想搜索事件對象以找到與位置字段的輸入相匹配的鍵“城市”(該位置從天氣API中加載數據)。 。
var bandData;
var locationData;
$(document).ready(function() {
$("#get-weather").click(function(e){
e.preventDefault();
//prevent empty fields
if($.trim($('#artist-search').val()) == ''){
$(".error").css("display", "block").html("input cannot be left
blank");
} else {
$(".error").css("display", "none");
//artist field
var artistField = $("#artist-search").val();
$.getJSON("https://rest.bandsintown.com/artists/"+artistField+"/events?
app_id="+bandKey, function(response){
console.log(response);
bandData = response;
});
//location field
var locationField = $("#location").val();
$.getJSON("http://api.openweathermap.org/data/2.5/weather?q="+locationField+",us&units=imperial&APPID="+weatherKey,
function(data){
console.log(data);
locationData = data;
});
};
});
});
JSON:
{
"id": "21023151",
"artist_id": "7931668",
"url": "https://www.bandsintown.com/e/URLinfo",
"on_sale_datetime": "",
"datetime": "2018-04-14T12:00:00",
"description":"",
"venue": {
"name": "Coachella Music and Arts Festival",
"latitude": "33.680015",
"longitude": "-116.23722",
"city": "Indio",
"region": "CA",
"country": "United States"
},
"offers": [
{
"type": "Tickets",
"url": "https://www.bandsintown.com/t/URLinfo",
"status": "available"
}
],
"lineup": [
"Post Malone"
]
}
我該怎么做才能根據用戶輸入的城市來過濾JSON數據? 並且,如果未返回任何內容,則打印“無結果”之類的內容。 當前,當我console.log“ bandData”和“ locationData”時,我得到一個未定義的值。
您可以通過地圖/過濾器執行以下操作
var locationField = $("#location").val();
$.getJSON("http://api.openweathermap.org/data/2.5/weather?q="+locationField+",us&units=imperial&APPID="+weatherKey,
function(data){
var FilteredData = data.filter(fundtion(elem){return (elem.venue.city == locationField) });
if(FilteredData.length){
console.log(FilteredData );
locationData = FilteredData ;
}
else{
console.log("No Data");
}
});
};
如果添加一些錯誤處理(如空檢查等),那將永遠是件好事。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.