Reputation: 107
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");
res.send(result);
};
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?
Upvotes: 0
Views: 431
Reputation: 371019
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:
req.body
, ortest.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");
res.send(payload);
};
Upvotes: 2