TypeError: data.filter is not a function

Issue

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?

Solution

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);
}

Answered By – Sello Mkantjwa

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published