Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: data.filter is not a function

I am trying to filter an array of JSON objects, which I get from an API call on my proxy. I am using a Node.js web framework Express to make the API call.

API returns the following:

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

server.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

What is the obvious mistake here? Anyone?

like image 431
PineCone Avatar asked Dec 07 '25 08:12

PineCone


1 Answers

I think your mistake is to think than res is the data than you expect.

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

so you must get datafrom the res and use it.

For example:

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

Have a nice day !

like image 149
Adrien De Peretti Avatar answered Dec 09 '25 20:12

Adrien De Peretti