Uncaught TypeError: [Array].filter is not a function

Uncaught TypeError: [Array].filter is not a function

我正在尝试将数据从烧瓶 api 传递到 chart.js。我们正在使用 D3 进行 api 调用:

var queryUrl = "http://127.0.0.1:5000/api/1/GenderOverTime";
var searchResults = [];

d3.json(queryUrl).then(function (chart_data) {
  searchResults = chart_data;});
  setTimeout(function(){init()},50)

这是我们 运行 出错的部分:

function init(){
  console.log("searchResults: ", searchResults);
  let selector = d3.select("#selDataset");
  let options = []
  filtered_data_for_chart = searchResults.filter(result=>{
      if (!options.includes(result.Sport)){
          options.push(result.Sport)
          selector
          .append("option")
          .text(result.Sport)
          .property("value", result.Sport);
      }
      
      return result.Sport==="Gymnastics"
  });

在 运行 init() 上,我们得到“ChartJSfile.js:14 未捕获的类型错误:searchResults.filter 不是一个函数”。

在使用 api 之前,我们有另一个 js 脚本,其中包含保存为数组对象的完全相同的数据,并且图表和过滤器工作正常。

我们添加了 setTimeout 以留出一些时间来获取数据,因为在数据加载到数组之前 init() 运行。

数据样本:

[{
    "_id": {
      "$oid": "61589a22cd5cc36ad5fc8898"
    },
    "Sport": "Aeronautics",
    "Year": 1936,
    "Sex": "M",
    "Name": 1,
    "Bronze": 0,
    "Silver": 0,
    "Gold": 1,
    "No Win": 0,
    "Attempts": 1,
    "Wins": 1
  },... ]

您可以使用 Array.from() 从类数组或可迭代对象创建一个新的浅拷贝数组实例。所以这应该可以解决您的问题:

const searchResultsList = Array.from(searchResults)
filtered_data_for_chart = searchResultsList.filter(result=>{...})

您的代码似乎可以正常工作as you can see here

您可能希望对其进行重构,以确保在需要时能够访问搜索结果中的数据:

var queryUrl = "http://127.0.0.1:5000/api/1/GenderOverTime";
var searchResults = [];

d3.json(queryUrl).then(function (chart_data) {
  searchResults = chart_data;
  init(searchResults);
});


function init(results) {
  console.log("searchResults: ", results);
  let selector = d3.select("#selDataset");
  let options = [];
  filtered_data_for_chart = results.filter((result) => {
    if (!options.includes(result.Sport)) {
      options.push(result.Sport);
      selector
        .append("option")
        .text(result.Sport)
        .property("value", result.Sport);
    }

    return result.Sport === "Gymnastics";
  });
}