0

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

2 Answers 2

1

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)
        })
Sign up to request clarification or add additional context in comments.

Comments

0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.