从API过滤对象数组返回空数组

时间:2018-10-11 17:31:07

标签: javascript filtering

我有从NPS.gov网站上获得的一系列对象。我正在尝试仅按一个类别过滤它们。这是我能够存储在nationalParkAlerts数组中的示例数据:

0: {title: "Quincy Center T Station Closed Weekends August 25 to October 21", id: "1BF329E4-1DD8-B71B-0BAF135EA5D8A333", description: "The Quincy Center Subway ("T") Station will be clo…ink. Please call 617-770-1175 with any questions.", category: "Park Closure", url: "https://www.mbta.com/wollaston", …}
1: {title: "Strong Winds and Hazard Trees", id: "14782F36-1DD8-B71B-0BCA86558413B16E", description: "Because of recent fires and forest die-back, some …l away from stands of dead or fire damaged trees.", category: "Caution", url: "", …}
2: {title: "Precautions for Zika Virus", id: "0A624DA1-1DD8-B71B-0B010C099120ED6E", description: "There are no areas of ongoing, active transmission…ved shirts and long pants during your park visit.", category: "Information", 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);
}

由于某种原因,它一直给我一个空数组。我不知道为什么。

5 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

在定义endpoint并发出请求时,您似乎将api键添加到uri中。另外,您在filterAlerts()的{​​{1}}之外调用.then,因此它可能在解析json之前执行。

response.json

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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

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

尝试

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

});

相反。

答案 4 :(得分:0)

您应该在.then回调中过滤警报,因为Fetch API异步运行。您的过滤器功能最有可能在解析JSON之前运行。另外,您的终结点变量已经包含apikey,因此在获取时无需再次将其串联。

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