[Fixed] Use variables only if exists into a array filter express


I have an endpoint in express with some variables, each of them can be there or not, depending of the variables i have to do a filter function over a array and applie the rules coming fron the req.body.

Is there any way to apply if conditions inside the return of an filter function?

The code is this:

test.getModelsFile = async (req, res) => {
 let data = json;
 const SubModel = req.body.SubModel;
 const Years = req.body.Years;
 const Engine = req.body.Years;
 const Make = req.body.Make;

  let result = data.filter((x) => {
   return x.Make == Make(Years) && x.Years == Years && x.Engine == Engine && x.SubModel == SubModel;
result = await deleteRepeatedFromArray(result, "Model");

This will only work if those variables came from the req.body, if they are not it will return an error, what can i do?


Make an array of the properties you want to look over. Then you can use Array.prototype.every to check that, for every property, either:

  • It doesn’t exist in the req.body, or
  • It exists, and is equal to the property on the item being iterated over
test.getModelsFile = async (req, res) => {
   const properties = ['SubModel', 'Years', 'Engine', 'Make'];
   const result = json.filter(item => properties.every(
      prop => !req.body[prop] || req.body[prop] === item[prop]
   const payload = await deleteRepeatedFromArray(result, "Model");

Leave a Reply

(*) Required, Your email will not be published