javascript 类型错误:data.filter 不是函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47306161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:17:59  来源:igfitidea点击:

TypeError: data.filter is not a function

javascriptexpressrequestjs

提问by shaz

I am trying to filter an arrayof JSONobjects, which I get from an APIcall on my proxy. I am using a Node.jsweb framework Expressto make the APIcall.

我试图来过滤arrayJSON对象,这是我从一个拿到API我的电话proxy。我正在使用Node.jsWeb 框架Express进行API调用。

API returns the following:

API 返回以下内容:

{
  data: [
    {
      type: "aaa",
      name: "Cycle",
      id: "c949up9c",
      category: ["A","B"]
    },
    {
      type: "bbb",
      name: "mobile",
      id: "c2rt4Jtu",
      category: ["C","D"]
    },
   ...
   ]
}

server.js

服务器.js

function sortDataByID(data) {
  return data.filter(function(item) {
     return item.id == 'c949up9c';
});
}

app.get('/products', (req, res) => {
 const options = {
 url: BASE_URL + '/products',
 headers: {
  'Authorization': 'hgjhgjh',
  'Accept': 'application/json'
 }
}
  request.get(options).pipe(sortDataByID(res));
});

I keep getting the following error message.

我不断收到以下错误消息。

TypeError: data.filter is not a function

类型错误:data.filter 不是函数

What is the obvious mistake here? Anyone?

这里明显的错误是什么?任何人?

采纳答案by Sello Mkantjwa

I've personally never seen piping to a function. I don't think that should work. In any case:

我个人从未见过管道到函数。我不认为那应该奏效。任何状况之下:

You can use a callback instead of piping. Try this:

您可以使用回调而不是管道。试试这个:

app.get('/products', (req, res) => {
 const options = {
 url: BASE_URL + '/products',
 json: true, //little convenience flag to set the requisite JSON headers
 headers: {
  'Authorization': 'hgjhgjh',
  'Accept': 'application/json'
 }
}
  request.get(options, sortDataByID);

});

});

function sortDataByID(err, response, data){ //the callback must take 3 parameters

    if(err){
        return res.json(err); //make sure there was no error
    }

    if(response.statusCode < 200 || response.statusCode > 299) { //Check for a non-error status code
        return res.status(400).json(err)
    }

    let dataToReturn =  data.data.filter(function(item) { //data.data because you need to access the data property on the response body.
        return item.id == 'c949up9c';
    }

    res.json(dataToReturn);
}

回答by Adrien De Peretti

I think your mistake is to think than resis the datathan you expect.

我认为你的错误是认为比resdata比您预期。

But if you take a look inside resyou should find the data.

但是如果你看看里面,res你应该会发现data.

so you must get datafrom the resand use it.

所以你必须得datares并使用它。

For example:

例如:

const data = res.data;
request.get(options).pipe(sortDataByID(data))

Have a nice day !

祝你今天过得愉快 !