Reputation: 1536
I'm working on nodejs and I want to check if my object property is not null when uses a filter :
propositions = propositions.filter((prop) => {
return prop.issuer.city.equals(req.user.city._id);
});
prop.issuer
may be null some time and I want to avoid this comparison when it's null!
I tried this but it's not worked :
propositions = propositions.filter((prop) => {
return prop.issuer?.city.equals(req.user.city._id);
});
Upvotes: 0
Views: 1100
Reputation: 191
The ?. syntax you used is next generation JS and not supported by all browsers (not sure if it supported in Node or not, but if it is, probably not supported in all versions of Node).
return prop.issuer?.city.equals(req.user.city._id)
You can just use simple if statements to overcome this problem though (that is what happens behind the scenes in NextGen JS tools like Babel).
Below is an example:
propositions = propositions.filter(prop => {
//this if will allow all items with props.issuer to pass through
//could return false if you want to filter out anything without prop.issuer instead
//Note null==undefined in JavaScript, don't need to check both
if(prop.issuer==undefined){return true;}
//below will only be made if prop.issuer is not null or undefined
return prop.issuer.city.equals(req.user.city._id)
})
Upvotes: 1
Reputation: 15797
propositions = propositions.filter(prop => prop.issuer ? prop.issuer.city.equals(req.user.city._id) : false)
I assumed you want to filter out propositions with null
issuer, that's why I used false
as third operand of ternary operator; if I was wrong, use true
.
Upvotes: 0