Javascript 从返回空数组的API筛选对象数组

Javascript 从返回空数组的API筛选对象数组,javascript,filtering,Javascript,Filtering,我从NPS.gov网站上获得了一系列对象。我试图通过一个类别来过滤它们。以下是我能够存储在nationalParkAlerts阵列中的示例数据: 0:{标题:“昆西中心T站8月25日至10月21日周末关闭”,id:“1BF329E4-1DD8-B71B-0BAF135EA5D8A333”,描述:“昆西中心地铁(“T”)站将关闭。如有任何问题,请致电617-770-1175。”,类别:“公园关闭”,url:https://www.mbta.com/wollaston", …} 1:{标题:“强风和

我从NPS.gov网站上获得了一系列对象。我试图通过一个类别来过滤它们。以下是我能够存储在nationalParkAlerts阵列中的示例数据:

0:{标题:“昆西中心T站8月25日至10月21日周末关闭”,id:“1BF329E4-1DD8-B71B-0BAF135EA5D8A333”,描述:“昆西中心地铁(“T”)站将关闭。如有任何问题,请致电617-770-1175。”,类别:“公园关闭”,url:https://www.mbta.com/wollaston", …}
1:{标题:“强风和危险树木”,id:“14782F36-1DD8-B71B-0BCA86558413B16E”,描述:“由于最近的火灾和森林死灰复燃,一些……远离死亡或火灾破坏的树木。”类别:“警告”,url:,…]
2:{标题:“寨卡病毒的预防措施”,id:“0A624DA1-1DD8-B71B-0B010C099120ED6E”,描述:“在公园参观期间,没有持续、活跃的传播区域……ved衬衫和长裤。”类别:“信息”,url:https://www.nps.gov/articles/zika-virus.htm", …}
下面是我正在使用的代码:

const endpoint = 'https://api.nps.gov/api/v1/alerts?limit=50&api_key=' + apikey;
const nationalParkAlerts = [];

fetch(endpoint + apikey).then(function (response) {
  response.json().then(function (alertsResponse) {
    nationalParkAlerts.push(...alertsResponse.data);
  });
  filterAlerts();
});

// console.log(nationalParkAlerts);

function filterAlerts() {
  console.log(nationalParkAlerts);

  const filteredAlerts = nationalParkAlerts.filter(function (onlyAlerts) {
    return onlyAlerts.category === "Caution";
  });
  console.log("alerts that have been filtered");
  console.log(filteredAlerts);
}

出于某种原因,它一直给我一个空数组。我不明白为什么

在定义
端点和发出请求时,似乎将api键添加到uri中。您还可以在
之外调用
filterAlerts()
。然后调用
response.json的
,因此它可能会在解析json之前执行

fetch(endpoint) // Removed the + apiKey that already happend
.then(function (response) {
    response.json().then(function (alertsResponse) {
        nationalParkAlerts.push(...alertsResponse.data);
        filterAlerts(); // Call it here when the json is parsed
    });
    // filterAlerts(); this gets called before the .then of response.json
});

如果您试图显示已注释的console.log的位置,它可能不会显示,因为它是异步的。尝试在回调中使用它。

这是因为您的filterAlerts函数在加载实际数据之前调用。尝试将其放入
回调中,然后
回调

问题是在填充
nationalParkAlerts
数组之前执行
filterAlerts()
,因为Fetch API的
json()
函数是异步工作的

最重要的是,您将向URL添加两次API密钥

试一试


相反。

您应该过滤
中的警报。然后
回调,因为Fetch API是异步运行的。过滤函数很可能在解析JSON之前运行。此外,端点变量已经包含apikey,因此在获取时不需要再次连接它

fetch(endpoint).then(function(response) {
    response.json().then(function(alertsResponse) {
        nationalParkAlerts.push(...alertsResponse.data);
        filterAlerts();
     });
});

由于
json()
是异步的,您需要将
filterAlerts()
放在它的
then()
中,这样它只在解析json后运行。首先,检查您是否设置了两次apiKey,它已经在变量端点上,然后调用
fetch(endpoint+apiKey)
fetch(endpoint).then(function(response) {
    response.json().then(function(alertsResponse) {
        nationalParkAlerts.push(...alertsResponse.data);
        filterAlerts();
     });
});