javascriptexpressrequestjs

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?


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